SPB Git

Repository Public

api.ts 3.6 KB 100 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : apps/web/src/lib/api.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Client de l'API. Le navigateur ne calcule jamais de score : il affiche ce que le serveur renvoie. */4445export class ApiError extends Error {46  status: number;47  code: string;48  constructor(status: number, code: string, message: string) {49    super(message);50    this.status = status;51    this.code = code;52  }53}5455export interface RequestOptions {56  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";57  body?: unknown;58  /** Identifiant (public) de la partie ; le jeton reste dans un témoin HttpOnly. */59  game?: string | null;60  signal?: AbortSignal;61}6263export async function api<T>(path: string, options: RequestOptions = {}): Promise<T> {64  const headers: Record<string, string> = { accept: "application/json", "x-requested-with": "gdi" };65  if (options.body !== undefined) headers["content-type"] = "application/json";66  if (options.game) headers["x-game"] = options.game;67  let response: Response;68  try {69    response = await fetch(path, {70      method: options.method ?? "GET",71      headers,72      body: options.body === undefined ? undefined : JSON.stringify(options.body),73      credentials: "same-origin",74      signal: options.signal,75    });76  } catch (error) {77    if ((error as Error).name === "AbortError") throw error;78    throw new ApiError(0, "offline", "Connexion interrompue. Votre partie est sauvegardée : nous réessayons.");79  }80  if (response.ok) return (await response.json()) as T;81  let code = "error";82  let message = "Une erreur est survenue.";83  try {84    const data = (await response.json()) as { error?: { code?: string; message?: string } };85    code = data.error?.code ?? code;86    message = data.error?.message ?? message;87  } catch {88    /* réponse non JSON */89  }90  throw new ApiError(response.status, code, message);91}9293export function imageUrl(id: string, width: 480 | 960 | 1600): string {94  return `/img/${id}/${width}`;95}9697export function imageSrcSet(id: string): string {98  return `${imageUrl(id, 480)} 480w, ${imageUrl(id, 960)} 960w, ${imageUrl(id, 1600)} 1600w`;99}100
Files main
Menu

Theme