From 03b58e7b0a960945bfd493068679fe325f3d7593 Mon Sep 17 00:00:00 2001 From: Djalim Simaila Date: Wed, 22 Apr 2026 13:24:03 +0200 Subject: [PATCH] feat(admin/api/users): add GET and POST endpoints for users --- routes/(apps)/admin/api/users.ts | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 routes/(apps)/admin/api/users.ts diff --git a/routes/(apps)/admin/api/users.ts b/routes/(apps)/admin/api/users.ts new file mode 100644 index 0000000..931795a --- /dev/null +++ b/routes/(apps)/admin/api/users.ts @@ -0,0 +1,60 @@ +import { FreshContext, Handlers } from "$fresh/server.ts"; +import { db } from "$root/databases/db.ts"; +import { users } from "$root/databases/schema.ts"; +import { AuthenticatedState } from "$root/defaults/interfaces.ts"; +import { eq } from "npm:drizzle-orm"; + +export const handler: Handlers = { + // #60 GET /users + async GET( + request: Request, + _context: FreshContext, + ): Promise { + const url = new URL(request.url); + const idRole = url.searchParams.get("idRole"); + + const rows = idRole + ? await db.select().from(users).where(eq(users.idRole, Number(idRole))) + : await db.select().from(users); + + return new Response(JSON.stringify(rows), { + headers: { "content-type": "application/json" }, + }); + }, + + // #61 POST /users + async POST( + request: Request, + _context: FreshContext, + ): Promise { + const body: { id: string; nom: string; prenom: string; idRole: number } = + await request.json(); + + if (!body.id || !body.nom || !body.prenom) { + return new Response(null, { status: 400 }); + } + + const existing = await db + .select() + .from(users) + .where(eq(users.id, body.id)) + .then((rows) => rows[0] ?? null); + + if (existing) { + return new Response( + JSON.stringify({ error: "Un utilisateur avec cet identifiant existe déjà" }), + { status: 409, headers: { "content-type": "application/json" } }, + ); + } + + const [created] = await db + .insert(users) + .values({ id: body.id, nom: body.nom, prenom: body.prenom, idRole: body.idRole }) + .returning(); + + return new Response(JSON.stringify(created), { + status: 201, + headers: { "content-type": "application/json" }, + }); + }, +};