WuYongJie d1c6efc79d
Some checks failed
CI Check / check (push) Has been cancelled
feat: NAS 部署与 Harbor 推送流程
2025-12-03 14:39:06 +08:00

113 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
// 点赞/取消点赞
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session) {
return NextResponse.json(
{ error: '请先登录' },
{ status: 401 }
)
}
const { materialId } = await req.json()
if (!materialId) {
return NextResponse.json(
{ error: '缺少素材ID' },
{ status: 400 }
)
}
const userId = (session.user as any).id
const material = await prisma.material.findUnique({
where: { id: materialId },
select: { userId: true },
})
if (!material) {
return NextResponse.json(
{ error: '素材不存在' },
{ status: 404 }
)
}
if (material.userId === userId) {
return NextResponse.json(
{ error: '不能给自己的素材点赞' },
{ status: 400 }
)
}
// 检查是否已点赞
const existingLike = await prisma.materialLike.findUnique({
where: {
materialId_userId: {
materialId,
userId
}
}
})
if (existingLike) {
// 取消点赞
await prisma.materialLike.delete({
where: {
id: existingLike.id
}
})
// 减少点赞次数
await prisma.material.update({
where: { id: materialId },
data: {
likeCount: {
decrement: 1
}
}
})
return NextResponse.json({
liked: false,
message: '已取消点赞'
})
} else {
// 添加点赞
await prisma.materialLike.create({
data: {
materialId,
userId
}
})
// 增加点赞次数
await prisma.material.update({
where: { id: materialId },
data: {
likeCount: {
increment: 1
}
}
})
return NextResponse.json({
liked: true,
message: '点赞成功'
})
}
} catch (error) {
console.error('Like error:', error)
return NextResponse.json(
{ error: '操作失败' },
{ status: 500 }
)
}
}