Files
back_end_oudelaa/oudelaa_dashboard/lib/auth/company-client.ts
boutmoun123 1b753a419a
API Gateway CI / Build, lint, and test (push) Successful in 13m33s
API Gateway CI / Build API Gateway image (push) Successful in 5m43s
feat: sync marketplace dashboard and staging CI
2026-11-02 17:28:58 +03:00

79 lines
2.5 KiB
TypeScript

import { ApiError, isHttpError, unwrapApiResponse } from "@/lib/api/response";
const API_PREFIX = "/api/proxy";
const CLIENT_TIMEOUT_MS = 20_000;
let refreshInFlight: Promise<boolean> | null = null;
function extractMessage(payload: unknown) {
if (!payload || typeof payload !== "object") return "";
const value = (payload as { message?: unknown }).message;
return Array.isArray(value) ? value.join(", ") : typeof value === "string" ? value : "";
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const isFormData = typeof FormData !== "undefined" && init?.body instanceof FormData;
const response = await fetch(`${API_PREFIX}${path}`, {
...init,
credentials: "include",
signal: init?.signal ?? AbortSignal.timeout(CLIENT_TIMEOUT_MS),
headers: {
"x-oudelaa-auth-scope": "company",
...(isFormData ? {} : { "Content-Type": "application/json" }),
...(init?.headers ?? {}),
},
});
if (!response.ok) {
const contentType = response.headers.get("content-type") ?? "";
const payload = contentType.includes("application/json")
? await response.json()
: await response.text();
const message = typeof payload === "string" ? payload : extractMessage(payload);
throw new ApiError(response.status, `${response.status}${message ? ` - ${message}` : ""}`);
}
if (response.status === 204) return undefined as T;
return unwrapApiResponse<T>(await response.json());
}
export async function loginCompany(email: string, password: string) {
return request<{ user?: { role?: string; name?: string; email?: string } }>("/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
}
async function runRefresh() {
try {
await request("/auth/refresh", { method: "POST", body: JSON.stringify({}) });
return true;
} catch (error) {
if (isHttpError(error, 400, 401)) return false;
throw error;
}
}
export function refreshCompany() {
if (!refreshInFlight) {
refreshInFlight = runRefresh().finally(() => {
refreshInFlight = null;
});
}
return refreshInFlight;
}
export async function companyFetch<T>(path: string, init?: RequestInit): Promise<T> {
try {
return await request<T>(path, init);
} catch (error) {
if (isHttpError(error, 401) && await refreshCompany()) {
return request<T>(path, init);
}
throw error;
}
}
export async function logoutCompany() {
await request("/auth/logout", { method: "POST", body: JSON.stringify({}) });
}