Spaces:
Running

WorkPilot-AI / web /src /lib /api.ts
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
3.37 kB
import {
getAccessToken,
getStepupToken,
notifySessionExpired,
refreshAccessToken,
} from "@/lib/session";
export const API_URL = (process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000").replace(
/\/$/,
"",
);
export class ApiError extends Error {
constructor(
public status: number,
public detail: string,
/** The parsed error body (e.g. a structured 422 ``detail``), when there is one. */
public body?: unknown,
) {
super(detail);
this.name = "ApiError";
}
}
export function detailOf(body: unknown, fallback: string): string {
if (body && typeof body === "object" && "detail" in body) {
const d = (body as { detail: unknown }).detail;
if (typeof d === "string") return d;
if (Array.isArray(d)) {
return d
.map((e) => (e && typeof e === "object" && "msg" in e ? String(e.msg) : JSON.stringify(e)))
.join("; ");
}
}
return fallback;
}
export interface RequestOptions {
method?: "GET" | "POST" | "PUT" | "DELETE";
body?: unknown;
signal?: AbortSignal;
/** Send the in-memory step-up token as X-Stepup-Token. */
stepup?: boolean;
query?: Record<string, string | number | boolean | null | undefined>;
}
export function buildUrl(path: string, query?: RequestOptions["query"]): string {
// API_URL may be same-origin relative ("/backend" behind the deploy/hf proxy).
const base = typeof window === "undefined" ? "http://127.0.0.1" : window.location.origin;
const url = new URL(path.startsWith("http") ? path : `${API_URL}${path}`, base);
for (const [k, v] of Object.entries(query ?? {})) {
if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));
}
return url.toString();
}
export async function authHeaders(stepup = false): Promise<Record<string, string>> {
const token = getAccessToken() ?? (await refreshAccessToken());
const h: Record<string, string> = {};
if (token) h.Authorization = `Bearer ${token}`;
const s = stepup ? getStepupToken() : null;
if (s) h["X-Stepup-Token"] = s;
return h;
}
/** Fetch JSON from the API with the in-memory bearer token. On a 401 it refreshes once
* (httpOnly cookie via the BFF) and retries; if that fails the session is over. */
export async function api<T>(path: string, opts: RequestOptions = {}): Promise<T> {
const send = async () =>
fetch(buildUrl(path, opts.query), {
method: opts.method ?? "GET",
headers: {
...(opts.body !== undefined ? { "Content-Type": "application/json" } : {}),
...(await authHeaders(opts.stepup)),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
signal: opts.signal,
cache: "no-store",
});
let res = await send();
if (res.status === 401) {
const token = await refreshAccessToken();
if (!token) {
notifySessionExpired();
throw new ApiError(401, "session expired");
}
res = await send();
}
const text = await res.text();
const body: unknown = text ? safeJson(text) : null;
if (!res.ok) throw new ApiError(res.status, detailOf(body, res.statusText || "request failed"), body);
return body as T;
}
function safeJson(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return text;
}
}