refactor: 引入 apiHandler + ApiError,消除 20 个路由的 try/catch 样板
- 新增 src/lib/api.ts:ApiError 错误类 + apiHandler 统一包装器 - 20 个 API 路由统一使用 apiHandler,删除重复的 try/catch 块 - 验证错误改用 throw new ApiError(),减少嵌套层级 - join/manage 路由的错误码映射改为直接抛出 ApiError - 删除已无引用的 errorResponse 辅助函数 - 净减 273 行代码
This commit is contained in:
@@ -1,13 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { apiHandler, ApiError } from "@/lib/api";
|
||||
|
||||
const MAX_HISTORY = 50;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
export const GET = apiHandler(async (req) => {
|
||||
const userId = req.nextUrl.searchParams.get("userId");
|
||||
if (!userId) {
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
if (!userId) return NextResponse.json([]);
|
||||
|
||||
const decisions = await prisma.decision.findMany({
|
||||
where: { userId },
|
||||
@@ -26,20 +25,18 @@ export async function GET(req: NextRequest) {
|
||||
createdAt: d.createdAt.toISOString(),
|
||||
})),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
export const POST = apiHandler(async (req) => {
|
||||
const { userId, roomId, restaurant, matchType, participants } =
|
||||
await req.json();
|
||||
|
||||
if (!userId || !roomId || !restaurant || !matchType) {
|
||||
return NextResponse.json({ error: "缺少必要字段" }, { status: 400 });
|
||||
throw new ApiError("缺少必要字段");
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: "用户未注册" }, { status: 404 });
|
||||
}
|
||||
if (!user) throw new ApiError("用户未注册", 404);
|
||||
|
||||
const existing = await prisma.decision.findFirst({
|
||||
where: { userId, roomId },
|
||||
@@ -73,4 +70,4 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
return NextResponse.json({ id: decision.id });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user