0595887480
- 新增 src/lib/api.ts:ApiError 错误类 + apiHandler 统一包装器 - 20 个 API 路由统一使用 apiHandler,删除重复的 try/catch 块 - 验证错误改用 throw new ApiError(),减少嵌套层级 - join/manage 路由的错误码映射改为直接抛出 ApiError - 删除已无引用的 errorResponse 辅助函数 - 净减 273 行代码
74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { apiHandler, ApiError } from "@/lib/api";
|
|
|
|
const MAX_HISTORY = 50;
|
|
|
|
export const GET = apiHandler(async (req) => {
|
|
const userId = req.nextUrl.searchParams.get("userId");
|
|
if (!userId) return NextResponse.json([]);
|
|
|
|
const decisions = await prisma.decision.findMany({
|
|
where: { userId },
|
|
orderBy: { createdAt: "desc" },
|
|
take: MAX_HISTORY,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
decisions.map((d) => ({
|
|
id: d.id,
|
|
roomId: d.roomId,
|
|
restaurantName: d.restaurantName,
|
|
restaurantData: JSON.parse(d.restaurantData),
|
|
matchType: d.matchType,
|
|
participants: d.participants,
|
|
createdAt: d.createdAt.toISOString(),
|
|
})),
|
|
);
|
|
});
|
|
|
|
export const POST = apiHandler(async (req) => {
|
|
const { userId, roomId, restaurant, matchType, participants } =
|
|
await req.json();
|
|
|
|
if (!userId || !roomId || !restaurant || !matchType) {
|
|
throw new ApiError("缺少必要字段");
|
|
}
|
|
|
|
const user = await prisma.user.findUnique({ where: { id: userId } });
|
|
if (!user) throw new ApiError("用户未注册", 404);
|
|
|
|
const existing = await prisma.decision.findFirst({
|
|
where: { userId, roomId },
|
|
});
|
|
if (existing) {
|
|
return NextResponse.json({ id: existing.id, alreadyExists: true });
|
|
}
|
|
|
|
const decision = await prisma.decision.create({
|
|
data: {
|
|
userId,
|
|
roomId,
|
|
restaurantName: restaurant.name,
|
|
restaurantData: JSON.stringify(restaurant),
|
|
matchType,
|
|
participants: participants ?? 1,
|
|
},
|
|
});
|
|
|
|
const count = await prisma.decision.count({ where: { userId } });
|
|
if (count > MAX_HISTORY) {
|
|
const oldest = await prisma.decision.findMany({
|
|
where: { userId },
|
|
orderBy: { createdAt: "asc" },
|
|
take: count - MAX_HISTORY,
|
|
select: { id: true },
|
|
});
|
|
await prisma.decision.deleteMany({
|
|
where: { id: { in: oldest.map((d) => d.id) } },
|
|
});
|
|
}
|
|
|
|
return NextResponse.json({ id: decision.id });
|
|
});
|