From 4eaea48ebd6d602cca6ba474e020bac360bb96ac Mon Sep 17 00:00:00 2001 From: Djalim Simaila Date: Wed, 22 Apr 2026 13:58:59 +0200 Subject: [PATCH] feat(students): add CRUD endpoints for student by numEtud --- .../(apps)/students/api/students/[numEtud].ts | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 routes/(apps)/students/api/students/[numEtud].ts diff --git a/routes/(apps)/students/api/students/[numEtud].ts b/routes/(apps)/students/api/students/[numEtud].ts new file mode 100644 index 0000000..bf0e64f --- /dev/null +++ b/routes/(apps)/students/api/students/[numEtud].ts @@ -0,0 +1,83 @@ +import { FreshContext, Handlers } from "$fresh/server.ts"; +import { db } from "$root/databases/db.ts"; +import { students } from "$root/databases/schema.ts"; +import { AuthenticatedState } from "$root/defaults/interfaces.ts"; +import { eq } from "npm:drizzle-orm"; + +const NOT_FOUND = new Response( + JSON.stringify({ error: "Ressource introuvable" }), + { status: 404, headers: { "content-type": "application/json" } }, +); + +const FORBIDDEN = new Response(null, { status: 403 }); + +export const handler: Handlers = { + // #10 GET /students/{numEtud} + async GET( + _request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const numEtud = Number(context.params.numEtud); + const student = await db + .select() + .from(students) + .where(eq(students.numEtud, numEtud)) + .then((rows) => rows[0] ?? null); + + if (!student) return NOT_FOUND; + + return new Response(JSON.stringify(student), { + headers: { "content-type": "application/json" }, + }); + }, + + // #11 PUT /students/{numEtud} + async PUT( + request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const numEtud = Number(context.params.numEtud); + const body: { nom: string; prenom: string; idPromo: string } = + await request.json(); + + const [updated] = await db + .update(students) + .set({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo }) + .where(eq(students.numEtud, numEtud)) + .returning(); + + if (!updated) return NOT_FOUND; + + return new Response(JSON.stringify(updated), { + headers: { "content-type": "application/json" }, + }); + }, + + // #12 DELETE /students/{numEtud} + async DELETE( + _request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const numEtud = Number(context.params.numEtud); + const [deleted] = await db + .delete(students) + .where(eq(students.numEtud, numEtud)) + .returning(); + + if (!deleted) return NOT_FOUND; + + return new Response(null, { status: 204 }); + }, +};