SPB Git forge

spb/immbot-ai

Public
1commits 1branches 0releases
1.5 MBsize
maindefault branch
20 days agolast push
TypeScript 98.3% CSS 0.9% Shell 0.7%
1.2 KB · 26 lines typescript
Raw Blame History
1// Utilitaires communs des routes API : gestion d'erreurs uniforme + validation zod.2import { NextResponse } from "next/server";3import { ZodError, type ZodType, type ZodTypeDef } from "zod";4import { AuthError } from "./auth/session.ts";5import { get } from "./db/index.ts";67export function apiError(e: unknown): NextResponse {8  if (e instanceof AuthError) return NextResponse.json({ error: e.message }, { status: e.status });9  if (e instanceof ZodError)10    return NextResponse.json({ error: "Requête invalide : " + e.issues.map((i) => i.message).join(" ; ") }, { status: 400 });11  console.error("[api]", e);12  return NextResponse.json({ error: "Erreur interne du serveur." }, { status: 500 });13}1415export async function parseBody<T>(req: Request, schema: ZodType<T, ZodTypeDef, unknown>): Promise<T> {16  const json = await req.json().catch(() => {17    throw new ZodError([{ code: "custom", message: "corps JSON manquant", path: [] }]);18  });19  return schema.parse(json);20}2122export function requireEnrollment(userId: number, courseCode: string) {23  const row = get("SELECT 1 as ok FROM enrollments WHERE user_id = ? AND course_code = ?", userId, courseCode);24  if (!row) throw new AuthError(403, "Vous n'êtes pas inscrit à ce cours.");25}26