File size: 4,479 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Typed REST client: openapi-fetch over the generated FastAPI schema (src/api/schema.d.ts, `npm run gen:api`).
// Same-origin cookie session; every unsafe request carries the CSRF token (double-submit cookie `fpt_csrf`).
import createClient, { type Middleware } from 'openapi-fetch';
import type { components, paths } from './schema';
import { explainError } from './errors';

export type Schemas = components['schemas'];

export class ApiError extends Error {
  status: number;
  code: string;
  requestId?: string | null;
  body: unknown;
  constructor(status: number, code: string, detail: string, body?: unknown, requestId?: string | null) {
    super(detail);
    this.status = status;
    this.code = code;
    this.body = body;
    this.requestId = requestId;
  }
}

const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);

export function readCookie(name: string, cookieString: string = typeof document !== 'undefined' ? document.cookie : ''): string | null {
  for (const part of cookieString.split(';')) {
    const [k, ...v] = part.trim().split('=');
    if (k === name) return decodeURIComponent(v.join('='));
  }
  return null;
}

let csrfOverride: string | null = null;
export function setCsrfToken(t: string | null) {
  csrfOverride = t;
}
export function csrfToken(): string | null {
  return readCookie('fpt_csrf') ?? csrfOverride;
}

export const csrfMiddleware: Middleware = {
  onRequest({ request }) {
    if (UNSAFE.has(request.method.toUpperCase())) {
      const t = csrfToken();
      if (t) request.headers.set('X-CSRF-Token', t);
    }
    return request;
  },
};

export function createApi(baseUrl = '', fetchImpl?: typeof fetch) {
  // Resolve fetch lazily (not at import time) so the browser's fetch, or a test double, is always the current one.
  const c = createClient<paths>({ baseUrl, credentials: 'same-origin', fetch: (req: Request) => (fetchImpl ?? globalThis.fetch)(req) });
  c.use(csrfMiddleware);
  return c;
}

export const api = createApi(typeof window !== 'undefined' ? window.location.origin : '');

type Result<T> = { data?: T; error?: unknown; response: Response };

/** Unwrap an openapi-fetch result into data or a typed ApiError (backend error model: {detail, code, request_id}). */
export async function unwrap<T>(p: Promise<Result<T>>): Promise<T> {
  const { data, error, response } = await p;
  if (response.ok) return (data ?? (undefined as T)) as T;
  const e = (error ?? {}) as { detail?: unknown; code?: string; request_id?: string };
  const detail = typeof e.detail === 'string' ? e.detail : `HTTP ${response.status}`;
  throw new ApiError(response.status, e.code ?? 'HTTP_ERROR', detail, error, e.request_id ?? response.headers.get('x-request-id'));
}

/** For endpoints whose payload is a dynamic dict (graph state views): typed by src/api/types.ts. */
export async function getJson<T>(url: string): Promise<T> {
  const r = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } });
  if (r.status === 204) return null as T;
  const body = await r.json().catch(() => ({}));
  if (!r.ok) throw new ApiError(r.status, body.code ?? 'HTTP_ERROR', body.detail ?? `HTTP ${r.status}`, body, body.request_id);
  return body as T;
}

/** An unsafe JSON request (with the CSRF header) for endpoints not yet in the generated schema. Errors become ApiError. */
export async function sendJson<T>(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE', url: string, body?: unknown): Promise<T> {
  const headers: Record<string, string> = { Accept: 'application/json', 'Content-Type': 'application/json' };
  const t = csrfToken();
  if (t) headers['X-CSRF-Token'] = t;
  const r = await fetch(url, { method, credentials: 'same-origin', headers, body: body === undefined ? undefined : JSON.stringify(body) });
  if (r.status === 204) return null as T;
  const out = await r.json().catch(() => ({}));
  if (!r.ok) throw new ApiError(r.status, out.code ?? 'HTTP_ERROR', typeof out.detail === 'string' ? out.detail : `HTTP ${r.status}`, out, out.request_id ?? r.headers.get('x-request-id'));
  return out as T;
}

/** The error in plain words (what happened, and what to do), never the raw code or request id. */
export function errorMessage(e: unknown): string {
  const i = explainError(e);
  return [i.message, i.fields?.map((f) => `${f.field}: ${f.message}`).join('; '), i.hint].filter(Boolean).join(' ');
}