You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

81 lines
2.0 KiB

import axios, { type InternalAxiosRequestConfig } from "axios";
import { authBridge } from "./auth-bridge";
import { getClientCookie } from "./cookies";
const PROXY_PATH_PARAM = "__proxyPath";
const LOCALHOST_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1"]);
function isAbsoluteUrl(url: string) {
return /^[a-z][a-z\d+\-.]*:\/\//i.test(url);
}
function shouldUseProxy() {
if (typeof window === "undefined") {
return false;
}
return true;
}
function withProxyPathParam(
params: InternalAxiosRequestConfig["params"],
proxyPath: string,
) {
if (params instanceof URLSearchParams) {
const nextParams = new URLSearchParams(params);
nextParams.set(PROXY_PATH_PARAM, proxyPath);
return nextParams;
}
if (typeof params === "string") {
const nextParams = new URLSearchParams(params);
nextParams.set(PROXY_PATH_PARAM, proxyPath);
return nextParams;
}
return {
...(params && typeof params === "object" ? params : {}),
[PROXY_PATH_PARAM]: proxyPath,
};
}
export function getApiRequestUrl(path: string) {
if (!isAbsoluteUrl(path) && shouldUseProxy()) {
const searchParams = new URLSearchParams({
[PROXY_PATH_PARAM]: path,
});
return `/api/proxy?${searchParams.toString()}`;
}
return `${process.env.NEXT_PUBLIC_API_BASE_URL}${path}`;
}
export const http = axios.create({
baseURL: shouldUseProxy() ? "/api/proxy" : process.env.NEXT_PUBLIC_API_BASE_URL,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
withCredentials: true,
});
http.interceptors.request.use((config) => {
const token = authBridge.getToken() ?? getClientCookie("HABIB_TOKEN");
if (token) {
config.headers.Authorization = `Token ${token}`;
}
if (shouldUseProxy() && config.url && !isAbsoluteUrl(config.url)) {
config.params = withProxyPathParam(config.params, config.url);
config.url = "";
}
return config;
});
http.interceptors.response.use(
(response) => response,
(error) => Promise.reject(error)
);