Files
slp-modular-cms/frontend/src/lib/api-client.ts
T
SluijsensandClaude Sonnet 5.5 2f3f7fbb2f Admin: gebruikerslijst blijft actueel, sessie blijft behouden bij tijdelijke refresh-fouten
- Refresh wist de sessie alleen nog bij 400/401/403; 429/5xx/netwerkfout behoudt hem (opstart: rustig opnieuw proberen met backoff, anders gast zonder het cookie te raken)
- Refresh is single-flight (opstart, 401-interceptor, profiel delen een lopende aanvraag)
- GET-verzoeken met cache: no-store; gebruikerslijst: refetch bij focus en poll 45 s; sessie ververst als de eigen rol in de lijst afwijkt

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:32:46 +01:00

179 lines
6.2 KiB
TypeScript

import { getAppConfig } from '@/lib/config';
// RFC 9457 ProblemDetails for standardized error handling.
export interface ProblemDetails {
type?: string;
title?: string;
status?: number;
detail?: string;
instance?: string;
// Extension members (e.g. traceId, errors).
[extension: string]: unknown;
}
// Convenience wrapper for API results (optional usage).
export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: ProblemDetails };
/**
* Typed error thrown for any non-2xx API response. Wraps an RFC 9457
* ProblemDetails body so callers can present context-aware messages
* (BR-U1-08, NFR-U1-05 / Q5-B) instead of raw stack traces.
*/
export class ProblemDetailsError extends Error {
readonly status: number;
readonly problem: ProblemDetails;
constructor(status: number, problem: ProblemDetails) {
super(problem.title ?? problem.detail ?? `Request failed with status ${status}`);
this.name = 'ProblemDetailsError';
this.status = status;
this.problem = problem;
}
}
/** Thrown when the network request itself fails (offline, timeout, DNS). */
export class NetworkError extends Error {
constructor(message = 'Network request failed') {
super(message);
this.name = 'NetworkError';
}
}
export interface RequestOptions extends Omit<RequestInit, 'body'> {
/** Parsed and JSON-serialized automatically when present. */
body?: unknown;
/** Skip the 401 refresh+retry interceptor (used by the refresh call itself). */
skipAuthRefresh?: boolean;
}
type RefreshHandler = () => Promise<string | null>;
type AuthFailureHandler = () => void;
/**
* Thin fetch wrapper. All calls send credentials so the httpOnly refresh
* cookie travels with the request (BR-U1-03). The access token is held only
* in memory and injected per request (BR-U1-02).
*/
export class ApiClient {
private readonly baseUrl: string;
private accessToken: string | null = null;
private refreshHandler: RefreshHandler | null = null;
private authFailureHandler: AuthFailureHandler | null = null;
constructor(baseUrl: string) {
this.baseUrl = baseUrl.replace(/\/$/, '');
}
setAccessToken(token: string | null): void {
this.accessToken = token;
}
/** Registered by AuthContext: performs a cookie-based refresh, returns the new token or null. */
setRefreshHandler(handler: RefreshHandler | null): void {
this.refreshHandler = handler;
}
/** Registered by AuthContext: invoked when refresh fails and auth must be cleared. */
setAuthFailureHandler(handler: AuthFailureHandler | null): void {
this.authFailureHandler = handler;
}
get<T>(path: string, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'GET' });
}
post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'POST', body });
}
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'PUT', body });
}
delete<T>(path: string, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'DELETE' });
}
private async request<T>(path: string, options: RequestOptions): Promise<T> {
let response = await this.rawFetch(path, options);
// 401 intercept: try a single cookie-based refresh, then retry once (BR-U1-04).
if (response.status === 401 && !options.skipAuthRefresh && this.refreshHandler !== null) {
let newToken: string | null = null;
let rejected = false;
try {
newToken = await this.refreshHandler();
rejected = newToken === null;
} catch {
// Transient (rate limit, restart, network): the session is not known to be gone, so it is not
// cleared; the caller gets the original 401.
}
if (newToken !== null) {
response = await this.rawFetch(path, options);
} else if (rejected) {
this.authFailureHandler?.();
}
}
return this.parse<T>(response);
}
private async rawFetch(path: string, options: RequestOptions): Promise<Response> {
const { body, skipAuthRefresh: _skip, headers, ...rest } = options;
const finalHeaders = new Headers(headers);
if (body !== undefined && body !== null) {
finalHeaders.set('Content-Type', 'application/json');
}
if (this.accessToken !== null) {
finalHeaders.set('Authorization', `Bearer ${this.accessToken}`);
}
try {
return await fetch(`${this.baseUrl}${path}`, {
...rest,
headers: finalHeaders,
credentials: 'include',
// A list read after a change must come from the server, never from an intermediate cache.
...(rest.method === 'GET' ? { cache: 'no-store' as const } : {}),
body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,
});
} catch (cause) {
throw new NetworkError(cause instanceof Error ? cause.message : undefined);
}
}
private async parse<T>(response: Response): Promise<T> {
if (response.status === 204) {
return undefined as T;
}
const text = await response.text();
const data = text.length > 0 ? safeJsonParse(text) : undefined;
if (!response.ok) {
const problem: ProblemDetails = isProblemDetails(data)
? data
: { status: response.status, title: response.statusText };
throw new ProblemDetailsError(response.status, problem);
}
return data as T;
}
}
function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return text;
}
}
function isProblemDetails(value: unknown): value is ProblemDetails {
return typeof value === 'object' && value !== null;
}
/** Shared singleton API client configured from the typed environment. */
export const api = new ApiClient(getAppConfig().apiBaseUrl);