79 lines
2.0 KiB
TypeScript
79 lines
2.0 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?.id) {
|
||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||
}
|
||
|
||
const { materialId } = await request.json();
|
||
|
||
if (!materialId) {
|
||
return NextResponse.json({ error: '缺少素材ID' }, { status: 400 });
|
||
}
|
||
|
||
const userId = session.user.id;
|
||
|
||
// 检查素材是否存在
|
||
const material = await prisma.material.findUnique({
|
||
where: { id: materialId },
|
||
});
|
||
|
||
if (!material) {
|
||
return NextResponse.json({ error: '素材不存在' }, { status: 404 });
|
||
}
|
||
|
||
// 检查是否已收藏
|
||
const existingFavorite = await prisma.materialFavorite.findFirst({
|
||
where: {
|
||
materialId,
|
||
userId,
|
||
},
|
||
});
|
||
|
||
if (existingFavorite) {
|
||
// 取消收藏
|
||
await prisma.materialFavorite.delete({
|
||
where: {
|
||
id: existingFavorite.id,
|
||
},
|
||
});
|
||
|
||
return NextResponse.json({
|
||
message: '已取消收藏',
|
||
isFavorited: false,
|
||
});
|
||
} else {
|
||
// 收藏
|
||
await prisma.materialFavorite.create({
|
||
data: {
|
||
materialId,
|
||
userId,
|
||
},
|
||
});
|
||
|
||
return NextResponse.json({
|
||
message: '已收藏',
|
||
isFavorited: true,
|
||
});
|
||
}
|
||
} catch (error: any) {
|
||
// 兼容旧版本数据库(没有material_favorites表)
|
||
if (error?.meta?.table?.includes('material_favorites')) {
|
||
return NextResponse.json(
|
||
{ error: '收藏功能需要先运行数据库迁移' },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
console.error('[Materials] FAVORITE error:', error);
|
||
return NextResponse.json({ error: '操作失败' }, { status: 500 });
|
||
}
|
||
}
|