tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

51 lignes · 1874 octetsBrut · Historique
1import { retryDelayMs, unexplainedMessage } from './game/errors';
2import type { ApiErrorBody, Envelope } from './types';
3
4type CallResult<T> =
5 | { ok: true; envelope: Envelope<T>; dryRun: boolean }
6 | { ok: false; error: ApiErrorBody };
7
8interface CallOptions {
9 dryRun?: boolean;
10 /** Sent as `Idempotency-Key` so a retried money move is applied once (federation deposit/withdraw). */
11 idempotencyKey?: string;
12}
13
14const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
15
16/**
17 * Client-side call through the same-origin proxy. `href` is an API path like `/v1/ships/ORION-1/dock`.
18 * Transient errors are retried once (see `retryDelayMs`).
19 */
20export async function callApi<T = unknown>(
21 method: string,
22 href: string,
23 body?: Record<string, unknown>,
24 { dryRun = false, idempotencyKey }: CallOptions = {}
25): Promise<CallResult<T>> {
26 const sep = href.includes('?') ? '&' : '?';
27 const url = `/api${href}${dryRun ? `${sep}dry_run=1` : ''}`;
28 const headers: Record<string, string> = {};
29 if (body) headers['content-type'] = 'application/json';
30 if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
31
32 for (let attempt = 0; ; attempt++) {
33 let res: Response;
34 try {
35 res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined });
36 } catch {
37 return { ok: false, error: { status: 0, code: 'network', message: 'Could not reach the server.' } };
38 }
39 const json = await res.json().catch(() => null);
40 if (res.ok) return { ok: true, envelope: json as Envelope<T>, dryRun };
41
42 const error: ApiErrorBody = json?.error ?? {
43 status: res.status,
44 code: 'unexplained',
45 message: unexplainedMessage(res.status, res.statusText)
46 };
47 const wait = attempt === 0 ? retryDelayMs(res.status, error.code, res.headers.get('retry-after')) : null;
48 if (wait === null) return { ok: false, error };
49 await sleep(wait);
50 }
51}