import { FreshContext, Handlers } from "$fresh/server.ts"; import { db } from "$root/databases/db.ts"; import { ueModules } from "$root/databases/schema.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { withRules } from "$root/defaults/withRules.ts"; import { and, eq } from "npm:drizzle-orm@0.45.2"; const NOT_FOUND = new Response( JSON.stringify({ error: "Association UE-Module introuvable" }), { status: 404, headers: { "content-type": "application/json" } }, ); const BAD_REQUEST = new Response( JSON.stringify({ error: "Paramètres invalides" }), { status: 400, headers: { "content-type": "application/json" } }, ); export const handler: Handlers = { // #39 GET /ue-modules/{idModule}/{idUE}/{idPromo} GET: withRules(["note_read"])(async (_request, context) => { const { idModule, idPromo } = (context as FreshContext) .params; const idUE = Number( (context as FreshContext).params.idUE, ); if (isNaN(idUE)) return BAD_REQUEST; const ueModuleAssociation = await db .select() .from(ueModules) .where( and( eq(ueModules.idModule, idModule), eq(ueModules.idUE, idUE), eq(ueModules.idPromo, idPromo), ), ) .then((rows) => rows[0] ?? null); if (!ueModuleAssociation) return NOT_FOUND; return new Response(JSON.stringify(ueModuleAssociation), { headers: { "content-type": "application/json" }, }); }), // #40 PUT /ue-modules/{idModule}/{idUE}/{idPromo} PUT: withRules(["note_write"])(async (request, context) => { const { idModule, idPromo } = (context as FreshContext) .params; const idUE = Number( (context as FreshContext).params.idUE, ); if (isNaN(idUE)) return BAD_REQUEST; const body: { coeff: number } = await request.json(); if (typeof body.coeff !== "number") { return new Response( JSON.stringify({ error: "Le champ 'coeff' doit être un nombre" }), { status: 400, headers: { "content-type": "application/json" } }, ); } const [updated] = await db .update(ueModules) .set({ coeff: body.coeff }) .where( and( eq(ueModules.idModule, idModule), eq(ueModules.idUE, idUE), eq(ueModules.idPromo, idPromo), ), ) .returning(); if (!updated) return NOT_FOUND; return new Response( JSON.stringify({ idModule: updated.idModule, idUE: updated.idUE, idPromo: updated.idPromo, coeff: updated.coeff, }), { headers: { "content-type": "application/json" } }, ); }), // #41 DELETE /ue-modules/{idModule}/{idUE}/{idPromo} DELETE: withRules(["note_write"])(async (_request, context) => { const { idModule, idPromo } = (context as FreshContext) .params; const idUE = Number( (context as FreshContext).params.idUE, ); if (isNaN(idUE)) return BAD_REQUEST; const [deleted] = await db .delete(ueModules) .where( and( eq(ueModules.idModule, idModule), eq(ueModules.idUE, idUE), eq(ueModules.idPromo, idPromo), ), ) .returning(); if (!deleted) return NOT_FOUND; return new Response(null, { status: 204 }); }), };