mirror of
https://github.com/fosrl/pangolin.git
synced 2026-02-14 08:56:39 +00:00
refactor and reorganize
This commit is contained in:
12
src/lib/api/cookies.ts
Normal file
12
src/lib/api/cookies.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export async function authCookieHeader() {
|
||||
const allCookies = await cookies();
|
||||
const cookieName = process.env.SESSION_COOKIE_NAME!;
|
||||
const sessionId = allCookies.get(cookieName)?.value ?? null;
|
||||
return {
|
||||
headers: {
|
||||
Cookie: `${cookieName}=${sessionId}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
8
src/lib/api/formatAxiosError.ts
Normal file
8
src/lib/api/formatAxiosError.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export function formatAxiosError(error: any, defaultMessage?: string): string {
|
||||
return (
|
||||
error.response?.data?.message ||
|
||||
error?.message ||
|
||||
defaultMessage ||
|
||||
"An error occurred"
|
||||
);
|
||||
}
|
||||
63
src/lib/api/index.ts
Normal file
63
src/lib/api/index.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { env } from "@app/lib/types/env";
|
||||
import axios, { AxiosInstance } from "axios";
|
||||
|
||||
let apiInstance: AxiosInstance | null = null;
|
||||
|
||||
export function createApiClient({ env }: { env: env }): AxiosInstance {
|
||||
if (apiInstance) {
|
||||
return apiInstance;
|
||||
}
|
||||
|
||||
if (typeof window === "undefined") {
|
||||
// @ts-ignore
|
||||
return;
|
||||
}
|
||||
|
||||
let baseURL;
|
||||
const suffix = "api/v1";
|
||||
|
||||
if (window.location.port === env.NEXT_PORT) {
|
||||
// this means the user is addressing the server directly
|
||||
baseURL = `${window.location.protocol}//${window.location.hostname}:${env.SERVER_EXTERNAL_PORT}/${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: {
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": "x-csrf-protection"
|
||||
}
|
||||
});
|
||||
|
||||
return apiInstance;
|
||||
}
|
||||
|
||||
// we can pull from env var here becuase it is only used in the server
|
||||
export const internal = axios.create({
|
||||
baseURL: `http://localhost:${process.env.SERVER_EXTERNAL_PORT}/api/v1`,
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": "x-csrf-protection"
|
||||
}
|
||||
});
|
||||
|
||||
export const priv = axios.create({
|
||||
baseURL: `http://localhost:${process.env.SERVER_INTERNAL_PORT}/api/v1`,
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
|
||||
export * from "./formatAxiosError";
|
||||
|
||||
Reference in New Issue
Block a user