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.

93 lignes · 3073 octetsBrut · Historique
1import { STARFLEET_API_URL } from '$app/env/private';
2import { retryDelayMs, unexplainedMessage } from '$lib/game/errors';
3import type { Envelope, ErrorEnvelope } from '$lib/types';
4
5export const API_BASE = STARFLEET_API_URL;
6
7export class ApiError extends Error {
8 constructor(
9 public status: number,
10 public code: string,
11 message: string,
12 public payload: ErrorEnvelope | null
13 ) {
14 super(message);
15 this.name = 'ApiError';
16 }
17}
18
19interface ApiOptions {
20 body?: unknown;
21 query?: Record<string, string | number | undefined>;
22 headers?: Record<string, string>;
23}
24
25const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
26
27/**
28 * Server-side call to the Starfleet API. Throws ApiError on non-2xx.
29 * Transient errors (contended, rate_limited, busy) are retried once — see `retryDelayMs`.
30 */
31export async function api<T>(
32 token: string,
33 method: string,
34 path: string,
35 opts: ApiOptions = {}
36): Promise<Envelope<T>> {
37 const url = new URL(`${API_BASE}${path.startsWith('/') ? path : `/${path}`}`);
38 for (const [k, v] of Object.entries(opts.query ?? {})) {
39 if (v !== undefined) url.searchParams.set(k, String(v));
40 }
41 const init: RequestInit = {
42 method,
43 headers: {
44 authorization: `Bearer ${token}`,
45 accept: 'application/json',
46 ...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
47 ...opts.headers
48 },
49 body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined
50 };
51
52 for (let attempt = 0; ; attempt++) {
53 let res: Response;
54 try {
55 res = await fetch(url, init);
56 } catch (e) {
57 console.error(`[api] ${method} ${url.pathname}: game server unreachable`, e);
58 throw new ApiError(502, 'unreachable', 'Could not reach the game server. Try again in a moment.', null);
59 }
60 const text = await res.text();
61 const json = parseJson(text) as Envelope<T> | ErrorEnvelope | null;
62 const err = json && 'error' in json ? json.error : undefined;
63
64 if (res.ok && json && !err) return json as Envelope<T>;
65
66 const wait = !res.ok && attempt === 0 ? retryDelayMs(res.status, err?.code ?? '', res.headers.get('retry-after')) : null;
67 if (wait !== null) {
68 await sleep(wait);
69 continue;
70 }
71 if (err) throw new ApiError(res.status, err.code, err.message, json as ErrorEnvelope);
72
73 // Not the game API speaking (a proxy or firewall page, an empty body): log who did,
74 // so the host's logs explain it. Never log the request headers: they carry the key.
75 console.error(
76 `[api] ${method} ${url.pathname} -> ${res.status} without an API envelope` +
77 ` (server: ${res.headers.get('server') ?? '?'}, cf-ray: ${res.headers.get('cf-ray') ?? '-'},` +
78 ` content-type: ${res.headers.get('content-type') ?? '?'}): ${text.slice(0, 200)}`
79 );
80 throw new ApiError(res.ok ? 502 : res.status, 'unexplained', unexplainedMessage(res.status, res.statusText), null);
81 }
82}
83
84function parseJson(text: string): unknown {
85 try {
86 return JSON.parse(text);
87 } catch {
88 return null;
89 }
90}
91
92export const get = <T>(token: string, path: string, query?: ApiOptions['query']) =>
93 api<T>(token, 'GET', path, { query });