69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
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@0.45.2";
|
|
|
|
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<null, AuthenticatedState> = {
|
|
// #65 GET /roles
|
|
async GET(
|
|
_request: Request,
|
|
_context: FreshContext<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
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<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
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" } },
|
|
);
|
|
},
|
|
};
|