import { Handlers } from "$fresh/server.ts"; import { db } from "../../../../databases/db.ts"; import { notes } from "../../../../databases/schema.ts"; import { withRules } from "$root/defaults/withRules.ts"; import { eq } from "npm:drizzle-orm@0.45.2"; export const handler: Handlers = { // #42 GET /notes GET: withRules(["note_read", "own_note"])(async (request, _context) => { const url = new URL(request.url); const numEtudParam = url.searchParams.get("numEtud"); const idModule = url.searchParams.get("idModule"); let query = db.select().from(notes).$dynamic(); if (numEtudParam) { const numEtud = parseInt(numEtudParam); if (isNaN(numEtud)) { return new Response("Paramètre numEtud invalide", { status: 400 }); } query = query.where(eq(notes.numEtud, numEtud)); } if (idModule) { query = query.where(eq(notes.idModule, idModule)); } const result = await query; return new Response(JSON.stringify(result), { status: 200, headers: { "Content-Type": "application/json" }, }); }), // #43 POST /notes POST: withRules(["note_write", "own_teaching_note"])( async (request, _context) => { const body = await request.json(); const { note, numEtud, idModule } = body; if (note === undefined || !numEtud || !idModule) { return new Response("Champs 'note', 'numEtud' et 'idModule' requis", { status: 400, }); } if (typeof note !== "number" || note < 0 || note > 20) { return new Response("Champ 'note' doit être un nombre entre 0 et 20", { status: 400, }); } const result = await db.insert(notes).values({ note, numEtud, idModule }) .returning(); return new Response(JSON.stringify(result[0]), { status: 201, headers: { "Content-Type": "application/json" }, }); }, ), };