diff --git a/routes/(apps)/students/api/promotions/[idPromo].ts b/routes/(apps)/students/api/promotions/[idPromo].ts new file mode 100644 index 0000000..25d71f3 --- /dev/null +++ b/routes/(apps)/students/api/promotions/[idPromo].ts @@ -0,0 +1,79 @@ +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 { 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 = { + // #15 GET /promotions/{idPromo} + async GET( + _request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const promo = await db + .select() + .from(promotions) + .where(eq(promotions.id, context.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} + async PUT( + request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const body: { annee: string } = await request.json(); + + const [updated] = await db + .update(promotions) + .set({ annee: body.annee }) + .where(eq(promotions.id, context.params.idPromo)) + .returning(); + + if (!updated) return NOT_FOUND; + + return new Response(JSON.stringify(updated), { + headers: { "content-type": "application/json" }, + }); + }, + + // #17 DELETE /promotions/{idPromo} + async DELETE( + _request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return FORBIDDEN; + } + + const [deleted] = await db + .delete(promotions) + .where(eq(promotions.id, context.params.idPromo)) + .returning(); + + if (!deleted) return NOT_FOUND; + + return new Response(null, { status: 204 }); + }, +};