diff --git a/routes/(apps)/admin/api/modules.ts b/routes/(apps)/admin/api/modules.ts new file mode 100644 index 0000000..582e215 --- /dev/null +++ b/routes/(apps)/admin/api/modules.ts @@ -0,0 +1,63 @@ +import { FreshContext, Handlers } from "$fresh/server.ts"; +import { db } from "$root/databases/db.ts"; +import { modules } from "$root/databases/schema.ts"; +import { AuthenticatedState } from "$root/defaults/interfaces.ts"; +import { eq } from "npm:drizzle-orm"; + +export const handler: Handlers = { + // #23 GET /modules + async GET( + _request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return new Response(JSON.stringify([]), { + headers: { "content-type": "application/json" }, + }); + } + + const rows = await db.select().from(modules); + return new Response(JSON.stringify(rows), { + headers: { "content-type": "application/json" }, + }); + }, + + // #24 POST /modules + async POST( + request: Request, + context: FreshContext, + ): Promise { + if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { + return new Response(null, { status: 403 }); + } + + const body: { id: string; nom: string } = await request.json(); + + if (!body.id || !body.nom) { + return new Response(null, { status: 400 }); + } + + const existing = await db + .select() + .from(modules) + .where(eq(modules.id, body.id)) + .then((rows) => rows[0] ?? null); + + if (existing) { + return new Response( + JSON.stringify({ error: "Un module avec cet identifiant existe déjà" }), + { status: 409, headers: { "content-type": "application/json" } }, + ); + } + + const [created] = await db + .insert(modules) + .values({ id: body.id, nom: body.nom }) + .returning(); + + return new Response(JSON.stringify(created), { + status: 201, + headers: { "content-type": "application/json" }, + }); + }, +};