SPB Git

Repository Public

http.ts 3.8 KB 93 lines typescript

1// Transport HTTP commun : session par cookie, en-tête anti-CSRF `X-SPMail: 1` (l'en-tête Origin est posée par le navigateur).2import { HttpError, NetworkError } from "./errors"34type UnauthorizedHandler = () => void5let onUnauthorized: UnauthorizedHandler = () => {}6/** Appelé pour toute réponse 401 : la session a expiré ou a été révoquée. */7export function setUnauthorizedHandler(fn: UnauthorizedHandler) {8  onUnauthorized = fn9}1011/** Code que le serveur donne à une requête sans session valide (server/src/session.ts). */12const NO_SESSION = "unauthenticated"13let verifying: Promise<void> | null = null14/**15 * Un 401 ne signifie « session perdue » que s'il vient de SP Mail. La passerelle relaie aussi les réponses du serveur de16 * courrier : une boîte retirée ou en cours de suppression y répond 401 sans que la session soit en cause. Dans le doute, on17 * vérifie la session elle-même avant de renvoyer la personne à l'écran de connexion.18 */19export function sessionLost(code: string) {20  if (code === NO_SESSION) return onUnauthorized()21  verifying ??= fetch("/api/me", { headers: { accept: "application/json" }, credentials: "same-origin", cache: "no-store" })22    .then((r) => {23      if (r.status === 401) onUnauthorized()24    })25    .catch(() => {})26    .finally(() => {27      verifying = null28    })29}3031export interface RequestOptions {32  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"33  json?: unknown34  body?: BodyInit35  headers?: Record<string, string>36  signal?: AbortSignal37  /** ne pas déclencher le retour à l'écran de connexion sur 401 (utilisé par la vérification initiale) */38  quiet401?: boolean39  /** la requête survit à la fermeture ou au rechargement de la page */40  keepalive?: boolean41}4243export async function request(url: string, opts: RequestOptions = {}): Promise<Response> {44  const headers: Record<string, string> = { accept: "application/json", ...opts.headers }45  const method = opts.method ?? "GET"46  if (method !== "GET") headers["x-spmail"] = "1"47  let body = opts.body48  if (opts.json !== undefined) {49    headers["content-type"] = "application/json"50    body = JSON.stringify(opts.json)51  }52  let r: Response53  try {54    r = await fetch(url, { method, headers, body, credentials: "same-origin", cache: "no-store", signal: opts.signal, keepalive: opts.keepalive })55  } catch (e) {56    if (e instanceof DOMException && e.name === "AbortError") throw e57    throw new NetworkError()58  }59  if (!r.ok) {60    let code = `http_${r.status}`61    let message: string | undefined62    let details: unknown63    try {64      // deux enveloppes : historique `{error, message}` et /api/v1 `{error: {code, message, details}}`65      const j = (await r.json()) as { error?: string | { code?: string; message?: string; details?: unknown }; message?: string }66      if (typeof j.error === "string") {67        code = j.error68        message = j.message69      } else if (j.error && typeof j.error === "object") {70        if (j.error.code) code = j.error.code71        message = j.error.message72        details = j.error.details73      }74    } catch {75      /* corps non JSON */76    }77    if (r.status === 401 && !opts.quiet401) sessionLost(code)78    throw new HttpError(r.status, code, message, details)79  }80  return r81}8283export async function api<T>(url: string, opts: RequestOptions = {}): Promise<T> {84  const r = await request(url, opts)85  return (await r.json()) as T86}8788export const apiGet = <T>(url: string, signal?: AbortSignal) => api<T>(url, { signal })89export const apiPost = <T>(url: string, json: unknown = {}) => api<T>(url, { method: "POST", json })90export const apiPut = <T>(url: string, json: unknown) => api<T>(url, { method: "PUT", json })91export const apiPatch = <T>(url: string, json: unknown) => api<T>(url, { method: "PATCH", json })92export const apiDelete = <T>(url: string) => api<T>(url, { method: "DELETE" })93
Files main
Menu

Theme