Files
PolyMPR/routes/(apps)/students/api/students.ts
T
djalim 49bcc3083a
Check Deno code / Check Deno code (push) Has been cancelled
Tests / Unit tests (push) Has been cancelled
Tests / Integration tests (push) Has been cancelled
fix: faculty users are now recognized as employees
2026-05-05 15:29:02 +02:00

74 lines
1.9 KiB
TypeScript

import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { students } from "$root/databases/schema.ts";
import { AuthenticatedState, isEmployee } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2";
export const handler: Handlers<null, AuthenticatedState> = {
// #7 GET /students
async GET(
request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (!isEmployee(context.state.session)) {
return new Response(JSON.stringify([]), {
headers: { "content-type": "application/json" },
});
}
const url = new URL(request.url);
const idPromo = url.searchParams.get("idPromo");
const rows = idPromo
? await db.select().from(students).where(eq(students.idPromo, idPromo))
: await db.select().from(students);
return new Response(JSON.stringify(rows), {
headers: { "content-type": "application/json" },
});
},
// #8 POST /students
async POST(
request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (!isEmployee(context.state.session)) {
return new Response(null, { status: 403 });
}
const body: {
numEtud: number;
nom: string;
prenom: string;
idPromo: string;
} = await request.json();
if (!body.nom || !body.prenom) {
return new Response(null, { status: 400 });
}
const values: {
numEtud?: number;
nom: string;
prenom: string;
idPromo?: string;
} = {
nom: body.nom,
prenom: body.prenom,
};
if (body.numEtud) values.numEtud = body.numEtud;
if (body.idPromo) values.idPromo = body.idPromo;
const [created] = await db
.insert(students)
.values(values)
.returning();
return new Response(JSON.stringify(created), {
status: 201,
headers: { "content-type": "application/json" },
});
},
};