70 lines
1.7 KiB
TypeScript
70 lines
1.7 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/lib/auth';
|
|
import { prisma } from '@/lib/prisma';
|
|
|
|
// POST - 点赞/取消点赞
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session?.user) {
|
|
return NextResponse.json({ error: '请先登录' }, { status: 401 });
|
|
}
|
|
|
|
const { materialId } = await request.json();
|
|
|
|
if (!materialId) {
|
|
return NextResponse.json({ error: '缺少素材ID' }, { status: 400 });
|
|
}
|
|
|
|
const userId = (session.user as any).id;
|
|
|
|
// 检查是否已点赞
|
|
const existingLike = await prisma.materialLike.findFirst({
|
|
where: {
|
|
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 });
|
|
}
|
|
}
|