add: api routes

This commit is contained in:
Elie Baier 2023-12-05 23:53:23 +01:00
parent 771c28fa32
commit fe914efa41
2 changed files with 92 additions and 1 deletions

View File

@ -4,8 +4,80 @@ import prisma from "@/lib/prisma";
interface IBody { interface IBody {
key: string key: string
grade: number grade: number
testId: number
} }
export async function POST(req: Request){ 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
}
});
} }

View File

@ -3,6 +3,7 @@ import prisma from "@/lib/prisma";
export async function GET(req: NextRequest){ export async function GET(req: NextRequest){
const date = req.nextUrl.searchParams.get("date"); const date = req.nextUrl.searchParams.get("date");
const key = req.nextUrl.searchParams.get("key");
const test = await prisma.test.findFirst({ const test = await prisma.test.findFirst({
select: { select: {
@ -15,6 +16,18 @@ export async function GET(req: NextRequest){
lastName: true, lastName: true,
isTeacher: true isTeacher: true
} }
},
grades: {
select: {
note: true,
grade: true,
createdAt: true,
},
where: {
user: {
key: key || ""
}
}
} }
}, },
where: { where: {
@ -33,6 +46,12 @@ export async function GET(req: NextRequest){
firstName: test.testOf.firstName, firstName: test.testOf.firstName,
lastName: test.testOf.lastName, lastName: test.testOf.lastName,
isTeacher: test.testOf.isTeacher 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
} }
}); });
} }