From fe914efa4120907f9fe61703c07f261b2cfc8fef Mon Sep 17 00:00:00 2001 From: Fayorg Date: Tue, 5 Dec 2023 23:53:23 +0100 Subject: [PATCH] add: api routes --- app/api/grade/route.ts | 74 +++++++++++++++++++++++++++++++++++++++++- app/api/test/route.ts | 19 +++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/app/api/grade/route.ts b/app/api/grade/route.ts index 5a491fb..233c945 100644 --- a/app/api/grade/route.ts +++ b/app/api/grade/route.ts @@ -4,8 +4,80 @@ import prisma from "@/lib/prisma"; interface IBody { key: string grade: number + testId: number } export async function POST(req: Request){ - return NextResponse.json({message: 'Server error'}, {status: 500}) + const body: IBody = await req.json(); + + const test = await prisma.test.findFirst({ + select: { + id: true, + testOn: true, + testOf: { + select: { + id: true, + firstName: true, + lastName: true, + isTeacher: true + } + }, + grades: { + select: { + note: true, + grade: true, + createdAt: true, + }, + where: { + user: { + key: body.key + } + } + } + }, + where: { + id: body.testId + } + }); + + if(!test){ + return NextResponse.json({error: "Test not found"}, {status: 404}); + } + + if(test.grades.length > 0){ + return NextResponse.json({error: "You have already voted"}, {status: 403}); + } + + const grade = await prisma.grade.create({ + data: { + note: "", + grade: body.grade, + user: { + connect: { + key: body.key + } + }, + test: { + connect: { + id: test.id + } + } + } + }); + + return NextResponse.json({ + id: test.id, + testOn: test.testOn, + testOf: { + firstName: test.testOf.firstName, + lastName: test.testOf.lastName, + isTeacher: test.testOf.isTeacher + }, + vote: { + hasVoted: test.grades?.length > 0, + grade: grade.grade, + note: grade.note, + createdAt: grade.createdAt + } + }); } diff --git a/app/api/test/route.ts b/app/api/test/route.ts index ebff42d..0d7b03d 100644 --- a/app/api/test/route.ts +++ b/app/api/test/route.ts @@ -3,6 +3,7 @@ import prisma from "@/lib/prisma"; export async function GET(req: NextRequest){ const date = req.nextUrl.searchParams.get("date"); + const key = req.nextUrl.searchParams.get("key"); const test = await prisma.test.findFirst({ select: { @@ -15,6 +16,18 @@ export async function GET(req: NextRequest){ lastName: true, isTeacher: true } + }, + grades: { + select: { + note: true, + grade: true, + createdAt: true, + }, + where: { + user: { + key: key || "" + } + } } }, where: { @@ -33,6 +46,12 @@ export async function GET(req: NextRequest){ firstName: test.testOf.firstName, lastName: test.testOf.lastName, isTeacher: test.testOf.isTeacher + }, + vote: { + hasVoted: test.grades?.length > 0, + grade: test.grades[0]?.grade, + note: test.grades[0]?.note, + createdAt: test.grades[0]?.createdAt } }); }