46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { prisma } from '@/lib/prisma'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions)
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: '未登录' }, { status: 401 })
|
|
}
|
|
|
|
const { materialId } = await req.json()
|
|
if (!materialId) {
|
|
return NextResponse.json({ error: '缺少素材ID' }, { status: 400 })
|
|
}
|
|
|
|
const existing = await prisma.materialFavorite.findFirst({
|
|
where: {
|
|
materialId,
|
|
userId: session.user.id,
|
|
},
|
|
})
|
|
|
|
if (existing) {
|
|
await prisma.materialFavorite.delete({ where: { id: existing.id } })
|
|
return NextResponse.json({ favorited: false })
|
|
}
|
|
|
|
await prisma.materialFavorite.create({
|
|
data: {
|
|
materialId,
|
|
userId: session.user.id,
|
|
},
|
|
})
|
|
|
|
return NextResponse.json({ favorited: true })
|
|
} catch (error) {
|
|
console.error('[MaterialFavorite] POST error:', error)
|
|
return NextResponse.json({ error: '更新收藏失败' }, { status: 500 })
|
|
}
|
|
}
|
|
|