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,64 +1,38 @@
|
||||
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 } = await req.json();
|
||||
|
||||
try {
|
||||
const { userId } = await req.json();
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "userId required" }, { status: 400 });
|
||||
if (!userId) throw new ApiError("userId required");
|
||||
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (data.kickedUsers.includes(userId)) {
|
||||
throw new ApiError("你已被移出该房间", 403);
|
||||
}
|
||||
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (data.kickedUsers.includes(userId)) {
|
||||
throw new Error("KICKED");
|
||||
}
|
||||
if (data.locked && !data.users.includes(userId)) {
|
||||
throw new Error("LOCKED");
|
||||
}
|
||||
if (!data.users.includes(userId)) {
|
||||
data.users.push(userId);
|
||||
}
|
||||
return data;
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
if (data.locked && !data.users.includes(userId)) {
|
||||
throw new ApiError("房间已锁定,无法加入", 403);
|
||||
}
|
||||
|
||||
notify(id);
|
||||
|
||||
return NextResponse.json({
|
||||
roomId: id,
|
||||
userCount: updated.users.length,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
if (e.message === "LOCKED") {
|
||||
return NextResponse.json(
|
||||
{ error: "房间已锁定,无法加入" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (e.message === "KICKED") {
|
||||
return NextResponse.json(
|
||||
{ error: "你已被移出该房间" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (!data.users.includes(userId)) {
|
||||
data.users.push(userId);
|
||||
}
|
||||
console.error("Failed to join room:", e);
|
||||
return data;
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "加入房间失败" },
|
||||
{ status: 500 },
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
notify(id);
|
||||
|
||||
return NextResponse.json({
|
||||
roomId: id,
|
||||
userCount: updated.users.length,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,106 +1,73 @@
|
||||
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, action, targetUserId } = await req.json();
|
||||
|
||||
try {
|
||||
const { userId, action, targetUserId } = await req.json();
|
||||
if (!userId || !action) {
|
||||
return NextResponse.json(
|
||||
{ error: "userId and action required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
if (!userId || !action) {
|
||||
throw new ApiError("userId and action required");
|
||||
}
|
||||
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (data.creatorId !== userId) {
|
||||
throw new ApiError("只有房主可以执行此操作", 403);
|
||||
}
|
||||
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (data.creatorId !== userId) {
|
||||
throw new Error("FORBIDDEN");
|
||||
}
|
||||
switch (action) {
|
||||
case "lock":
|
||||
data.locked = true;
|
||||
break;
|
||||
|
||||
switch (action) {
|
||||
case "lock":
|
||||
data.locked = true;
|
||||
break;
|
||||
case "unlock":
|
||||
data.locked = false;
|
||||
break;
|
||||
|
||||
case "unlock":
|
||||
data.locked = false;
|
||||
break;
|
||||
case "kick":
|
||||
if (!targetUserId || targetUserId === userId) {
|
||||
throw new ApiError("无效的操作对象");
|
||||
}
|
||||
data.users = data.users.filter((u) => u !== targetUserId);
|
||||
if (!data.kickedUsers.includes(targetUserId)) {
|
||||
data.kickedUsers.push(targetUserId);
|
||||
}
|
||||
delete data.swipeCounts[targetUserId];
|
||||
for (const rid of Object.keys(data.likes)) {
|
||||
data.likes[rid] = data.likes[rid].filter(
|
||||
(u) => u !== targetUserId,
|
||||
);
|
||||
}
|
||||
if (
|
||||
data.match &&
|
||||
data.likes[data.match]?.length !== data.users.length
|
||||
) {
|
||||
data.match = null;
|
||||
}
|
||||
break;
|
||||
|
||||
case "kick":
|
||||
if (!targetUserId || targetUserId === userId) {
|
||||
throw new Error("INVALID_TARGET");
|
||||
}
|
||||
data.users = data.users.filter((u) => u !== targetUserId);
|
||||
if (!data.kickedUsers.includes(targetUserId)) {
|
||||
data.kickedUsers.push(targetUserId);
|
||||
}
|
||||
delete data.swipeCounts[targetUserId];
|
||||
for (const rid of Object.keys(data.likes)) {
|
||||
data.likes[rid] = data.likes[rid].filter(
|
||||
(u) => u !== targetUserId,
|
||||
);
|
||||
}
|
||||
if (
|
||||
data.match &&
|
||||
data.likes[data.match]?.length !== data.users.length
|
||||
) {
|
||||
data.match = null;
|
||||
}
|
||||
break;
|
||||
case "end_voting":
|
||||
for (const u of data.users) {
|
||||
data.swipeCounts[u] = data.restaurants.length;
|
||||
}
|
||||
break;
|
||||
|
||||
case "end_voting":
|
||||
for (const u of data.users) {
|
||||
data.swipeCounts[u] = data.restaurants.length;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error("UNKNOWN_ACTION");
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
default:
|
||||
throw new ApiError("未知操作");
|
||||
}
|
||||
|
||||
notify(id);
|
||||
return data;
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
if (e.message === "FORBIDDEN") {
|
||||
return NextResponse.json(
|
||||
{ error: "只有房主可以执行此操作" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (e.message === "INVALID_TARGET") {
|
||||
return NextResponse.json(
|
||||
{ error: "无效的操作对象" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (e.message === "UNKNOWN_ACTION") {
|
||||
return NextResponse.json(
|
||||
{ error: "未知操作" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
console.error("Failed to manage room:", e);
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "操作失败" },
|
||||
{ status: 500 },
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
notify(id);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { atomicUpdateRoom } from "@/lib/store";
|
||||
import { notify } from "@/lib/roomEvents";
|
||||
import { apiHandler } 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;
|
||||
|
||||
let restaurantIds: string[] | undefined;
|
||||
@@ -18,33 +16,25 @@ export async function POST(
|
||||
// No body or invalid JSON — plain reset
|
||||
}
|
||||
|
||||
try {
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (restaurantIds && restaurantIds.length > 0) {
|
||||
const idSet = new Set(restaurantIds);
|
||||
data.restaurants = data.restaurants.filter((r) => idSet.has(r.id));
|
||||
}
|
||||
data.likes = {};
|
||||
data.swipeCounts = {};
|
||||
data.match = null;
|
||||
return data;
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
const updated = await atomicUpdateRoom(id, (data) => {
|
||||
if (restaurantIds && restaurantIds.length > 0) {
|
||||
const idSet = new Set(restaurantIds);
|
||||
data.restaurants = data.restaurants.filter((r) => idSet.has(r.id));
|
||||
}
|
||||
data.likes = {};
|
||||
data.swipeCounts = {};
|
||||
data.match = null;
|
||||
return data;
|
||||
});
|
||||
|
||||
notify(id);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error("Failed to reset room:", e);
|
||||
if (!updated) {
|
||||
return NextResponse.json(
|
||||
{ error: "重置失败" },
|
||||
{ status: 500 },
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
notify(id);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -1,28 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { buildRoomStatus } from "@/lib/buildRoomStatus";
|
||||
import { apiHandler } from "@/lib/api";
|
||||
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
export const GET = apiHandler(async (_req, { params }) => {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const status = await buildRoomStatus(id);
|
||||
const status = await buildRoomStatus(id);
|
||||
|
||||
if (!status) {
|
||||
return NextResponse.json(
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(status);
|
||||
} catch (e) {
|
||||
console.error("Failed to get room:", e);
|
||||
if (!status) {
|
||||
return NextResponse.json(
|
||||
{ error: "获取房间信息失败" },
|
||||
{ status: 500 },
|
||||
{ error: "房间不存在或已过期" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(status);
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user