import { Handlers } from "$fresh/server.ts"; import { db } from "../../../../../../databases/db.ts"; import { notes } from "../../../../../../databases/schema.ts"; import { and, eq } from "npm:drizzle-orm@0.45.2"; export const handler: Handlers = { // #45 GET /notes/:numEtud/:idModule async GET(_request, context) { try { const numEtud = parseInt(context.params.numEtud); const { idModule } = context.params; if (isNaN(numEtud)) { return new Response( JSON.stringify({ error: "Paramètre numEtud invalide" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const result = await db.select().from(notes).where( and( eq(notes.numEtud, numEtud), eq(notes.idModule, idModule), ), ); if (result.length === 0) { return new Response( JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } return new Response(JSON.stringify(result[0]), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error fetching note:", error); return new Response("Failed to fetch data", { status: 500 }); } }, // #46 PUT /notes/:numEtud/:idModule async PUT(request, context) { try { const numEtud = parseInt(context.params.numEtud); const { idModule } = context.params; if (isNaN(numEtud)) { return new Response( JSON.stringify({ error: "Paramètre numEtud invalide" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const body = await request.json(); const { note } = body; if (note === undefined) { return new Response("Champ 'note' manquant", { status: 400 }); } const result = await db.update(notes).set({ note }).where( and( eq(notes.numEtud, numEtud), eq(notes.idModule, idModule), ), ).returning(); if (result.length === 0) { return new Response( JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } return new Response(JSON.stringify(result[0]), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error updating note:", error); return new Response("Failed to update note", { status: 500 }); } }, // #47 DELETE /notes/:numEtud/:idModule async DELETE(_request, context) { try { const numEtud = parseInt(context.params.numEtud); const { idModule } = context.params; if (isNaN(numEtud)) { return new Response( JSON.stringify({ error: "Paramètre numEtud invalide" }), { status: 400, headers: { "Content-Type": "application/json" }, }, ); } const result = await db.delete(notes).where( and( eq(notes.numEtud, numEtud), eq(notes.idModule, idModule), ), ).returning(); if (result.length === 0) { return new Response( JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } return new Response(null, { status: 204 }); } catch (error) { console.error("Error deleting note:", error); return new Response("Failed to delete note", { status: 500 }); } }, };