fosrl.pangolin/src/lib/api/index.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-01-04 20:22:01 -05:00
import { Env } from "@app/lib/types/env";
import axios, { AxiosInstance } from "axios";
2024-10-06 12:39:05 -04:00
let apiInstance: AxiosInstance | null = null;
2024-10-26 17:01:34 -04:00
2025-01-04 20:22:01 -05:00
export function createApiClient({ env }: { env: Env }): AxiosInstance {
if (apiInstance) {
return apiInstance;
}
if (typeof window === "undefined") {
// @ts-ignore
return;
2024-12-20 22:24:44 -05:00
}
let baseURL;
const suffix = "api/v1";
2025-01-04 20:22:01 -05:00
if (window.location.port === env.server.nextPort) {
// this means the user is addressing the server directly
2025-01-04 20:22:01 -05:00
baseURL = `${window.location.protocol}//${window.location.hostname}:${env.server.externalPort}/${suffix}`;
axios.defaults.withCredentials = true;
} else {
// user is accessing through a proxy
baseURL = window.location.origin + `/${suffix}`;
}
if (!baseURL) {
throw new Error("Failed to create api client, invalid environment");
}
apiInstance = axios.create({
baseURL,
timeout: 10000,
headers: {
2024-12-25 22:04:20 -05:00
"Content-Type": "application/json",
"X-CSRF-Token": "x-csrf-protection"
}
});
return apiInstance;
}
2024-10-06 22:09:30 -04:00
2024-10-26 17:13:30 -04:00
// we can pull from env var here becuase it is only used in the server
2024-10-06 22:09:30 -04:00
export const internal = axios.create({
2024-10-26 17:13:30 -04:00
baseURL: `http://localhost:${process.env.SERVER_EXTERNAL_PORT}/api/v1`,
2024-10-06 12:39:05 -04:00
timeout: 10000,
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": "x-csrf-protection"
}
2024-10-06 12:39:05 -04:00
});
export const priv = axios.create({
baseURL: `http://localhost:${process.env.SERVER_INTERNAL_PORT}/api/v1`,
timeout: 10000,
headers: {
"Content-Type": "application/json"
}
});
2025-01-01 21:41:31 -05:00
export * from "./formatAxiosError";