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
+37 -51
View File
@@ -1,69 +1,55 @@
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, action } = await req.json();
try {
const { userId, restaurantId, action } = await req.json();
if (!userId || restaurantId == null || !action) {
throw new ApiError("userId, restaurantId, and action are required");
}
if (!userId || restaurantId == null || !action) {
return NextResponse.json(
{ error: "userId, restaurantId, and action are required" },
{ status: 400 },
);
}
const rid = String(restaurantId);
const rid = String(restaurantId);
const updated = await atomicUpdateRoom(id, (data) => {
const restaurantIndex = data.restaurants.findIndex((r) => r.id === rid);
const alreadySwiped =
restaurantIndex >= 0 &&
restaurantIndex < (data.swipeCounts[userId] ?? 0);
const updated = await atomicUpdateRoom(id, (data) => {
const restaurantIndex = data.restaurants.findIndex((r) => r.id === rid);
const alreadySwiped =
restaurantIndex >= 0 &&
restaurantIndex < (data.swipeCounts[userId] ?? 0);
if (alreadySwiped) return data;
if (alreadySwiped) return data;
if (action === "like") {
if (!data.likes[rid]) {
data.likes[rid] = [];
}
if (!data.likes[rid].includes(userId)) {
data.likes[rid].push(userId);
}
if (data.likes[rid].length === data.users.length) {
data.match = rid;
}
if (action === "like") {
if (!data.likes[rid]) {
data.likes[rid] = [];
}
if (!data.likes[rid].includes(userId)) {
data.likes[rid].push(userId);
}
data.swipeCounts[userId] = (data.swipeCounts[userId] ?? 0) + 1;
return data;
});
if (!updated) {
return NextResponse.json(
{ error: "房间不存在或已过期" },
{ status: 404 },
);
if (data.likes[rid].length === data.users.length) {
data.match = rid;
}
}
notify(id);
data.swipeCounts[userId] = (data.swipeCounts[userId] ?? 0) + 1;
return NextResponse.json({
match: updated.match,
likeCount: updated.likes[rid]?.length ?? 0,
});
} catch (e) {
console.error("Failed to process swipe:", e);
return data;
});
if (!updated) {
return NextResponse.json(
{ error: "操作失败" },
{ status: 500 },
{ error: "房间不存在或已过期" },
{ status: 404 },
);
}
}
notify(id);
return NextResponse.json({
match: updated.match,
likeCount: updated.likes[rid]?.length ?? 0,
});
});