-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathroute.ts
More file actions
72 lines (61 loc) · 2.24 KB
/
Copy pathroute.ts
File metadata and controls
72 lines (61 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { auth } from '@clerk/nextjs/server'
import { NextRequest, NextResponse } from 'next/server'
import mongoose from 'mongoose'
import { connectDB } from '@/lib/mongodb'
import { Grade } from '@/models/Grade'
const ALLOWED_UPDATE_FIELDS = ['marks', 'maxMarks', 'grade']
export async function PUT(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { userId } = await auth()
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
try {
const { id } = await ctx.params
// Validate ObjectId
if (!mongoose.Types.ObjectId.isValid(id)) {
return NextResponse.json({ error: 'Invalid id' }, { status: 400 })
}
let body
try {
body = await req.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON in request body' }, { status: 400 })
}
// Sanitize: only allow whitelisted fields
const sanitizedBody: Record<string, unknown> = {}
for (const key of ALLOWED_UPDATE_FIELDS) {
if (key in body) {
sanitizedBody[key] = body[key]
}
}
await connectDB()
const grade = await Grade.findOneAndUpdate(
{ _id: id, teacherId: userId },
sanitizedBody,
{ new: true }
)
if (!grade) return NextResponse.json({ error: 'Not found' }, { status: 404 })
return NextResponse.json(grade)
} catch (error) {
if (error instanceof Error) {
console.error('PUT /api/grades/[id] error:', error.message)
}
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
export async function DELETE(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
const { userId } = await auth()
if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
try {
const { id } = await ctx.params
await connectDB()
const deleted = await Grade.findOneAndDelete({ _id: id, teacherId: userId })
if (!deleted) {
return NextResponse.json({ error: 'Grade not found' }, { status: 404 })
}
return NextResponse.json({ success: true })
} catch (error) {
if (error instanceof Error) {
console.error('DELETE /api/grades/[id] error:', error.message)
}
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}