nxtgauge-frontend-solid/src/lib/server/gateway.ts

47 lines
1.5 KiB
TypeScript

const gatewayBase = (process.env.NEXT_PUBLIC_API_URL || process.env.PUBLIC_API_URL || 'http://localhost:3005/api').replace(/\/+$/, '');
export function gatewayUrl(path: string) {
const normalized = path.startsWith('/') ? path : `/${path}`;
if (gatewayBase.endsWith('/api')) {
if (normalized === '/api') return gatewayBase;
if (normalized.startsWith('/api/')) {
return `${gatewayBase}${normalized.slice(4)}`;
}
}
return `${gatewayBase}${normalized}`;
}
export function readAccessTokenFromRequest(request: Request): string | null {
const cookie = request.headers.get('cookie') || '';
if (!cookie) return null;
const parts = cookie.split(';').map((part) => part.trim());
const pair = parts.find((part) => part.startsWith('nxtgauge_access_token='));
if (!pair) return null;
const token = pair.split('=').slice(1).join('=').trim();
if (!token) return null;
try {
return decodeURIComponent(token);
} catch {
return token;
}
}
export function withAuthHeaders(request: Request, extra?: Record<string, string>) {
const token = readAccessTokenFromRequest(request);
const headers: Record<string, string> = { ...(extra || {}) };
if (token) headers.Authorization = `Bearer ${token}`;
return headers;
}
// Alias for forwardAuth (used in some API endpoints)
export const forwardAuth = withAuthHeaders;
// Forward cookies from request
export function forwardCookies(request: Request): Record<string, string> {
const cookie = request.headers.get('cookie');
if (!cookie) return {};
return { cookie };
}