96 lines
2.6 KiB
TypeScript
96 lines
2.6 KiB
TypeScript
import { Handlers } from "$fresh/server.ts";
|
|
import { db } from "../../../../databases/db.ts";
|
|
import { notes } from "../../../../databases/schema.ts";
|
|
import { eq } from "npm:drizzle-orm@0.45.2";
|
|
|
|
export const handler: Handlers = {
|
|
// #42 GET /notes
|
|
async GET(request) {
|
|
try {
|
|
const url = new URL(request.url);
|
|
const numEtudParam = url.searchParams.get("numEtud");
|
|
const idModule = url.searchParams.get("idModule");
|
|
|
|
let query = db.select().from(notes).$dynamic();
|
|
|
|
if (numEtudParam) {
|
|
const numEtud = parseInt(numEtudParam);
|
|
if (isNaN(numEtud)) {
|
|
return new Response("Paramètre numEtud invalide", { status: 400 });
|
|
}
|
|
query = query.where(eq(notes.numEtud, numEtud));
|
|
}
|
|
|
|
if (idModule) {
|
|
query = query.where(eq(notes.idModule, idModule));
|
|
}
|
|
|
|
const result = await query;
|
|
|
|
return new Response(JSON.stringify(result), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
} catch (error) {
|
|
console.error("Error fetching notes:", error);
|
|
return new Response("Failed to fetch data", { status: 500 });
|
|
}
|
|
},
|
|
|
|
// #43 POST /notes
|
|
async POST(request) {
|
|
try {
|
|
const body = await request.json();
|
|
const { note, numEtud, idModule, noteSession2 } = body;
|
|
|
|
if (note === undefined || !numEtud || !idModule) {
|
|
return new Response("Champs 'note', 'numEtud' et 'idModule' requis", {
|
|
status: 400,
|
|
});
|
|
}
|
|
|
|
if (typeof note !== "number" || note < 0 || note > 20) {
|
|
return new Response("Champ 'note' doit être un nombre entre 0 et 20", {
|
|
status: 400,
|
|
});
|
|
}
|
|
|
|
if (
|
|
noteSession2 !== undefined && noteSession2 !== null &&
|
|
(typeof noteSession2 !== "number" || noteSession2 < 0 ||
|
|
noteSession2 > 20)
|
|
) {
|
|
return new Response(
|
|
"Champ 'noteSession2' doit être un nombre entre 0 et 20",
|
|
{ status: 400 },
|
|
);
|
|
}
|
|
|
|
const values: {
|
|
note: number;
|
|
numEtud: number;
|
|
idModule: string;
|
|
noteSession2?: number | null;
|
|
} = {
|
|
note,
|
|
numEtud,
|
|
idModule,
|
|
};
|
|
if (noteSession2 !== undefined) {
|
|
values.noteSession2 = noteSession2;
|
|
}
|
|
|
|
const result = await db.insert(notes).values(values)
|
|
.returning();
|
|
|
|
return new Response(JSON.stringify(result[0]), {
|
|
status: 201,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
} catch (error) {
|
|
console.error("Error creating note:", error);
|
|
return new Response("Failed to create note", { status: 500 });
|
|
}
|
|
},
|
|
};
|