diff --git a/routes/(apps)/admin/api/roles.ts b/routes/(apps)/admin/api/roles.ts new file mode 100644 index 0000000..59688c8 --- /dev/null +++ b/routes/(apps)/admin/api/roles.ts @@ -0,0 +1,64 @@ +import { FreshContext, Handlers } from "$fresh/server.ts"; +import { db } from "$root/databases/db.ts"; +import { rolePermissions, roles } from "$root/databases/schema.ts"; +import { AuthenticatedState } from "$root/defaults/interfaces.ts"; +import { eq } from "npm:drizzle-orm"; + +async function getRoleWithPermissions( + id: number, +): Promise<{ id: number; nom: string; permissions: string[] } | null> { + const role = await db + .select() + .from(roles) + .where(eq(roles.id, id)) + .then((rows) => rows[0] ?? null); + + if (!role) return null; + + const perms = await db + .select({ idPermission: rolePermissions.idPermission }) + .from(rolePermissions) + .where(eq(rolePermissions.idRole, id)); + + return { id: role.id, nom: role.nom, permissions: perms.map((p) => p.idPermission) }; +} + +export const handler: Handlers = { + // #65 GET /roles + async GET( + _request: Request, + _context: FreshContext, + ): Promise { + const allRoles = await db.select().from(roles); + + const result = await Promise.all( + allRoles.map((r) => getRoleWithPermissions(r.id)), + ); + + return new Response(JSON.stringify(result), { + headers: { "content-type": "application/json" }, + }); + }, + + // #66 POST /roles + async POST( + request: Request, + _context: FreshContext, + ): Promise { + const body: { nom: string } = await request.json(); + + if (!body.nom) { + return new Response(null, { status: 400 }); + } + + const [created] = await db + .insert(roles) + .values({ nom: body.nom }) + .returning(); + + return new Response( + JSON.stringify({ id: created.id, nom: created.nom, permissions: [] }), + { status: 201, headers: { "content-type": "application/json" } }, + ); + }, +};