101 lines
2.7 KiB
TypeScript
101 lines
2.7 KiB
TypeScript
import { prisma } from "@/lib/prisma";
|
|
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "@/lib/auth";
|
|
import { NextResponse } from "next/server";
|
|
|
|
export async function GET(
|
|
_request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "请先登录" }, { status: 401 });
|
|
}
|
|
|
|
const collectionId = parseInt(params.id);
|
|
const userId = parseInt(session.user.id);
|
|
|
|
const collection = await prisma.collection.findUnique({
|
|
where: { id: collectionId },
|
|
include: { _count: { select: { items: true } } },
|
|
});
|
|
|
|
if (!collection || collection.userId !== userId) {
|
|
return NextResponse.json({ error: "收藏夹不存在或无权限" }, { status: 403 });
|
|
}
|
|
|
|
return NextResponse.json(collection);
|
|
}
|
|
|
|
export async function PUT(
|
|
request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "请先登录" }, { status: 401 });
|
|
}
|
|
|
|
const collectionId = parseInt(params.id);
|
|
const userId = parseInt(session.user.id);
|
|
|
|
const existing = await prisma.collection.findUnique({
|
|
where: { id: collectionId },
|
|
});
|
|
|
|
if (!existing || existing.userId !== userId) {
|
|
return NextResponse.json({ error: "收藏夹不存在或无权限" }, { status: 403 });
|
|
}
|
|
|
|
const body = await request.json();
|
|
const { name, description } = body;
|
|
|
|
const data: any = {};
|
|
if (name !== undefined) {
|
|
if (!name.trim()) {
|
|
return NextResponse.json({ error: "名称不能为空" }, { status: 400 });
|
|
}
|
|
if (name.trim().length > 50) {
|
|
return NextResponse.json({ error: "名称不能超过50个字符" }, { status: 400 });
|
|
}
|
|
data.name = name.trim();
|
|
}
|
|
if (description !== undefined) {
|
|
data.description = description?.trim() || null;
|
|
}
|
|
|
|
const collection = await prisma.collection.update({
|
|
where: { id: collectionId },
|
|
data,
|
|
});
|
|
|
|
return NextResponse.json(collection);
|
|
}
|
|
|
|
export async function DELETE(
|
|
_request: Request,
|
|
{ params }: { params: { id: string } }
|
|
) {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: "请先登录" }, { status: 401 });
|
|
}
|
|
|
|
const collectionId = parseInt(params.id);
|
|
const userId = parseInt(session.user.id);
|
|
|
|
const existing = await prisma.collection.findUnique({
|
|
where: { id: collectionId },
|
|
});
|
|
|
|
if (!existing || existing.userId !== userId) {
|
|
return NextResponse.json({ error: "收藏夹不存在或无权限" }, { status: 403 });
|
|
}
|
|
|
|
await prisma.collection.delete({
|
|
where: { id: collectionId },
|
|
});
|
|
|
|
return NextResponse.json({ success: true });
|
|
}
|