import { FreshContext, Handlers } from "$fresh/server.ts"; import { db } from "$root/databases/db.ts"; import { promotions } from "$root/databases/schema.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { withRules } from "$root/defaults/withRules.ts"; import { eq } from "npm:drizzle-orm@0.45.2"; const NOT_FOUND = new Response( JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } }, ); export const handler: Handlers = { // #15 GET /promotions/{idPromo} GET: withRules(["student_read"])(async (_request, context) => { const promo = await db .select() .from(promotions) .where( eq( promotions.id, (context as FreshContext).params.idPromo, ), ) .then((rows) => rows[0] ?? null); if (!promo) return NOT_FOUND; return new Response(JSON.stringify(promo), { headers: { "content-type": "application/json" }, }); }), // #16 PUT /promotions/{idPromo} PUT: withRules(["student_write"])(async (request, context) => { const body: { annee: string } = await request.json(); const [updated] = await db .update(promotions) .set({ annee: body.annee }) .where( eq( promotions.id, (context as FreshContext).params.idPromo, ), ) .returning(); if (!updated) return NOT_FOUND; return new Response(JSON.stringify(updated), { headers: { "content-type": "application/json" }, }); }), // #17 DELETE /promotions/{idPromo} DELETE: withRules(["student_write"])(async (_request, context) => { const [deleted] = await db .delete(promotions) .where( eq( promotions.id, (context as FreshContext).params.idPromo, ), ) .returning(); if (!deleted) return NOT_FOUND; return new Response(null, { status: 204 }); }), };