/** What the server answers when a call fails: `{"error": {"code", "message"}}`. */ export class ApiError extends Error { status: number code: string /** Seconds to wait before asking again, when the server said so (`Retry-After`). */ retryAfter?: number constructor(status: number, code: string, message: string, retryAfter?: number) { super(message) this.name = 'ApiError' this.status = status this.code = code this.retryAfter = retryAfter } } /** The session side of a call, injected so that this file never imports the session (which imports this). */ export interface AuthHooks { getAccessToken(): Promise /** Renews the session; resolves to the new access token, or null when there is nothing to renew. */ refresh(): Promise signOut(): void } let hooks: AuthHooks = { getAccessToken: async () => null, refresh: async () => null, signOut: () => {}, } export function setAuthHooks(next: AuthHooks): void { hooks = next } type QueryValue = string | number | boolean | undefined /** A list value is sent once for each item (`seed=1&seed=2`). */ type Query = Record export interface CallOptions { /** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */ auth?: boolean /** Lets the request finish after the page is closed (the browser allows it for small bodies). */ keepalive?: boolean /** Cancels the request. A cancelled call rejects with the browser's `AbortError`, not an `ApiError`. */ signal?: AbortSignal } const BASE = '/api/v1' function buildUrl(path: string, params?: Query): string { const query = new URLSearchParams() for (const [key, value] of Object.entries(params ?? {})) { for (const item of Array.isArray(value) ? value : [value]) { if (item !== undefined) query.append(key, String(item)) } } const text = query.toString() return `${BASE}${path}${text ? `?${text}` : ''}` } async function toApiError(res: Response): Promise { try { const body = (await res.json()) as { error?: { code?: string; message?: string } } return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText, retryAfter(res)) } catch { return new ApiError(res.status, 'unknown', res.statusText, retryAfter(res)) } } /** The `Retry-After` header in whole seconds, or nothing when it is absent or is a date. */ function retryAfter(res: Response): number | undefined { const text = res.headers.get('Retry-After') if (text === null || !/^\d+$/.test(text.trim())) return undefined return Number(text) } async function send( method: string, url: string, body: unknown, token: string | null, keepalive: boolean | undefined, signal: AbortSignal | undefined, ): Promise { const headers: Record = { Accept: 'application/json' } // A form (files) is sent as it is: the browser writes its content type, which carries the boundary. const form = body instanceof FormData if (body !== undefined && !form) headers['Content-Type'] = 'application/json' if (token) headers.Authorization = `Bearer ${token}` try { return await fetch(url, { method, headers, body: body === undefined ? undefined : form ? body : JSON.stringify(body), keepalive: keepalive || undefined, signal, }) } catch (e) { // A cancelled request is the caller's own doing: say so as it is, not as a broken connection. if (e instanceof DOMException && e.name === 'AbortError') throw e throw new ApiError(0, 'network', 'The server cannot be reached') } } async function request(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise { const auth = opts.auth ?? true const url = buildUrl(path, params) let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive, opts.signal) if (res.status === 401 && auth) { const fresh = await hooks.refresh() if (fresh) res = await send(method, url, body, fresh, opts.keepalive, opts.signal) if (res.status === 401) hooks.signOut() } if (!res.ok) throw await toApiError(res) if (res.status === 204) return undefined as T return (await res.json()) as T } export const api = { get: (path: string, params?: Query, opts: CallOptions = {}) => request('GET', path, params, undefined, opts), post: (path: string, body?: unknown, opts: CallOptions = {}) => request('POST', path, undefined, body ?? {}, opts), /** Sends files, as a form. */ upload: (path: string, form: FormData, opts: CallOptions = {}) => request('POST', path, undefined, form, opts), patch: (path: string, body?: unknown, opts: CallOptions = {}) => request('PATCH', path, undefined, body ?? {}, opts), put: (path: string, body?: unknown, opts: CallOptions = {}) => request('PUT', path, undefined, body ?? {}, opts), del: (path: string, opts: CallOptions = {}) => request('DELETE', path, undefined, undefined, opts), }