67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
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@0.45.2";
|
|
|
|
const NOT_FOUND = new Response(
|
|
JSON.stringify({ error: "Ressource introuvable" }),
|
|
{ status: 404, headers: { "content-type": "application/json" } },
|
|
);
|
|
|
|
export const handler: Handlers<null, AuthenticatedState> = {
|
|
// #62 GET /users/{id}
|
|
async GET(
|
|
_request: Request,
|
|
context: FreshContext<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
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<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
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<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
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 });
|
|
},
|
|
};
|