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:
2026-02-26 18:08:47 +08:00
parent d4c6da57a1
commit 0595887480
22 changed files with 626 additions and 863 deletions
+31 -45
View File
@@ -1,60 +1,46 @@
import { NextResponse } from "next/server";
import { atomicUpdateRoom } from "@/lib/store";
import { notify } from "@/lib/roomEvents";
import { apiHandler, ApiError } from "@/lib/api";
export async function POST(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
export const POST = apiHandler(async (req, { params }) => {
const { id } = await params;
const { userId, restaurantId } = await req.json();
try {
const { userId, restaurantId } = await req.json();
if (!userId || restaurantId == null) {
throw new ApiError("userId and restaurantId are required");
}
if (!userId || restaurantId == null) {
return NextResponse.json(
{ error: "userId and restaurantId are required" },
{ status: 400 },
);
const rid = String(restaurantId);
const updated = await atomicUpdateRoom(id, (data) => {
if (data.likes[rid]) {
data.likes[rid] = data.likes[rid].filter((u) => u !== userId);
if (data.likes[rid].length === 0) {
delete data.likes[rid];
}
}
const rid = String(restaurantId);
const updated = await atomicUpdateRoom(id, (data) => {
if (data.likes[rid]) {
data.likes[rid] = data.likes[rid].filter((u) => u !== userId);
if (data.likes[rid].length === 0) {
delete data.likes[rid];
}
}
if (data.match === rid) {
data.match = null;
}
const count = data.swipeCounts[userId] ?? 0;
if (count > 0) {
data.swipeCounts[userId] = count - 1;
}
return data;
});
if (!updated) {
return NextResponse.json(
{ error: "房间不存在或已过期" },
{ status: 404 },
);
if (data.match === rid) {
data.match = null;
}
notify(id);
const count = data.swipeCounts[userId] ?? 0;
if (count > 0) {
data.swipeCounts[userId] = count - 1;
}
return NextResponse.json({ ok: true });
} catch (e) {
console.error("Failed to undo swipe:", e);
return data;
});
if (!updated) {
return NextResponse.json(
{ error: "撤回失败" },
{ status: 500 },
{ error: "房间不存在或已过期" },
{ status: 404 },
);
}
}
notify(id);
return NextResponse.json({ ok: true });
});