62 lines
2.1 KiB
TypeScript
62 lines
2.1 KiB
TypeScript
import { cookies } from 'next/headers';
|
|
|
|
export const TOKEN_COOKIE = 'tower_token';
|
|
export const MEMBER_COOKIE = 'tower_member_token';
|
|
const MEMBER_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
|
|
|
export function getApiBaseUrl(): string {
|
|
return process.env['API_URL'] ?? 'http://localhost:3001';
|
|
}
|
|
|
|
export async function getToken(): Promise<string | undefined> {
|
|
const store = await cookies();
|
|
return store.get(TOKEN_COOKIE)?.value;
|
|
}
|
|
|
|
export async function getMemberToken(): Promise<string | undefined> {
|
|
const store = await cookies();
|
|
return store.get(MEMBER_COOKIE)?.value;
|
|
}
|
|
|
|
function withAuthHeader(headers: Headers, token: string | undefined): void {
|
|
headers.set('Accept', 'application/json');
|
|
if (token && !headers.has('Authorization')) {
|
|
headers.set('Authorization', `Bearer ${token}`);
|
|
}
|
|
}
|
|
|
|
export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
|
const token = await getToken();
|
|
const headers = new Headers(init.headers);
|
|
withAuthHeader(headers, token);
|
|
if (init.body && !headers.has('Content-Type')) {
|
|
headers.set('Content-Type', 'application/json');
|
|
}
|
|
return fetch(`${getApiBaseUrl()}${path}`, { ...init, headers, cache: 'no-store' });
|
|
}
|
|
|
|
export async function memberApiFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
|
const token = await getMemberToken();
|
|
const headers = new Headers(init.headers);
|
|
withAuthHeader(headers, token);
|
|
if (init.body && !headers.has('Content-Type')) {
|
|
headers.set('Content-Type', 'application/json');
|
|
}
|
|
return fetch(`${getApiBaseUrl()}${path}`, { ...init, headers, cache: 'no-store' });
|
|
}
|
|
|
|
export function buildMemberCookie(token: string): string {
|
|
return `${MEMBER_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${MEMBER_MAX_AGE_SECONDS}`;
|
|
}
|
|
|
|
export function clearMemberCookie(): string {
|
|
return `${MEMBER_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
|
|
}
|
|
|
|
export function jsonResponse(body: unknown, status = 200, extraHeaders: Record<string, string> = {}): Response {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json', ...extraHeaders },
|
|
});
|
|
}
|