From 5a86f69093cf8cdedd081eaaae0815788c64f099 Mon Sep 17 00:00:00 2001 From: Djalim Simaila Date: Wed, 22 Apr 2026 13:25:29 +0200 Subject: [PATCH] feat: add CRUD endpoints for users by id --- routes/(apps)/admin/api/users/[id].ts | 66 +++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 routes/(apps)/admin/api/users/[id].ts diff --git a/routes/(apps)/admin/api/users/[id].ts b/routes/(apps)/admin/api/users/[id].ts new file mode 100644 index 0000000..81c5871 --- /dev/null +++ b/routes/(apps)/admin/api/users/[id].ts @@ -0,0 +1,66 @@ +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"; + +const NOT_FOUND = new Response( + JSON.stringify({ error: "Ressource introuvable" }), + { status: 404, headers: { "content-type": "application/json" } }, +); + +export const handler: Handlers = { + // #62 GET /users/{id} + async GET( + _request: Request, + context: FreshContext, + ): Promise { + const user = await db + .select() + .from(users) + .where(eq(users.id, context.params.id)) + .then((rows) => rows[0] ?? null); + + if (!user) return NOT_FOUND; + + return new Response(JSON.stringify(user), { + headers: { "content-type": "application/json" }, + }); + }, + + // #63 PUT /users/{id} + async PUT( + request: Request, + context: FreshContext, + ): Promise { + const body: { nom: string; prenom: string; idRole: number } = + await request.json(); + + const [updated] = await db + .update(users) + .set({ nom: body.nom, prenom: body.prenom, idRole: body.idRole }) + .where(eq(users.id, context.params.id)) + .returning(); + + if (!updated) return NOT_FOUND; + + return new Response(JSON.stringify(updated), { + headers: { "content-type": "application/json" }, + }); + }, + + // #64 DELETE /users/{id} + async DELETE( + _request: Request, + context: FreshContext, + ): Promise { + const [deleted] = await db + .delete(users) + .where(eq(users.id, context.params.id)) + .returning(); + + if (!deleted) return NOT_FOUND; + + return new Response(null, { status: 204 }); + }, +}; -- 2.52.0