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
+76 -111
View File
@@ -1,130 +1,95 @@
import { NextRequest, NextResponse } from "next/server";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { errorResponse, validateMembership } from "@/lib/blindbox";
import { validateMembership } from "@/lib/blindbox";
import { apiHandler, ApiError } from "@/lib/api";
export async function POST(req: NextRequest) {
try {
const { roomId, userId, content } = await req.json();
export const POST = apiHandler(async (req) => {
const { roomId, userId, content } = await req.json();
if (!userId || typeof userId !== "string") {
return errorResponse("请先登录", 401);
}
if (!roomId || typeof roomId !== "string") {
return errorResponse("roomId 不能为空", 400);
}
if (!content || typeof content !== "string" || content.trim().length === 0) {
return errorResponse("内容不能为空", 400);
}
if (content.trim().length > 200) {
return errorResponse("内容不能超过 200 字", 400);
}
const isMember = await validateMembership(roomId, userId);
if (!isMember) {
return errorResponse("你不是这个房间的成员", 403);
}
const idea = await prisma.blindBoxIdea.create({
data: {
roomId,
userId,
content: content.trim(),
},
});
return NextResponse.json({ id: idea.id }, { status: 201 });
} catch {
return errorResponse("提交失败", 500);
if (!userId || typeof userId !== "string") throw new ApiError("请先登录", 401);
if (!roomId || typeof roomId !== "string") throw new ApiError("roomId 不能为空");
if (!content || typeof content !== "string" || content.trim().length === 0) {
throw new ApiError("内容不能为空");
}
}
if (content.trim().length > 200) throw new ApiError("内容不能超过 200 字");
export async function GET(req: NextRequest) {
const isMember = await validateMembership(roomId, userId);
if (!isMember) throw new ApiError("你不是这个房间的成员", 403);
const idea = await prisma.blindBoxIdea.create({
data: { roomId, userId, content: content.trim() },
});
return NextResponse.json({ id: idea.id }, { status: 201 });
});
export const GET = apiHandler(async (req) => {
const roomId = req.nextUrl.searchParams.get("roomId");
const userId = req.nextUrl.searchParams.get("userId");
if (!roomId) {
return errorResponse("缺少 roomId", 400);
}
if (!userId) {
return errorResponse("请先登录", 401);
}
if (!roomId) throw new ApiError("缺少 roomId");
if (!userId) throw new ApiError("请先登录", 401);
const isMember = await validateMembership(roomId, userId);
if (!isMember) {
return errorResponse("你不是这个房间的成员", 403);
if (!isMember) throw new ApiError("你不是这个房间的成员", 403);
const [poolCount, myIdeas, drawn] = await Promise.all([
prisma.blindBoxIdea.count({
where: { roomId, status: "in_pool" },
}),
prisma.blindBoxIdea.findMany({
where: { roomId, userId, status: "in_pool" },
orderBy: { createdAt: "desc" },
select: { id: true, content: true, createdAt: true },
}),
prisma.blindBoxIdea.findMany({
where: { roomId, status: "drawn" },
orderBy: { createdAt: "desc" },
include: {
user: { select: { id: true, username: true, avatar: true } },
drawnBy: { select: { id: true, username: true, avatar: true } },
},
}),
]);
return NextResponse.json({ poolCount, myIdeas, drawn });
});
export const PUT = apiHandler(async (req) => {
const { ideaId, userId, content } = await req.json();
if (!userId) throw new ApiError("请先登录", 401);
if (!ideaId) throw new ApiError("缺少 ideaId");
if (!content || typeof content !== "string" || content.trim().length === 0) {
throw new ApiError("内容不能为空");
}
if (content.trim().length > 200) throw new ApiError("内容不能超过 200 字");
try {
const [poolCount, myIdeas, drawn] = await Promise.all([
prisma.blindBoxIdea.count({
where: { roomId, status: "in_pool" },
}),
prisma.blindBoxIdea.findMany({
where: { roomId, userId, status: "in_pool" },
orderBy: { createdAt: "desc" },
select: { id: true, content: true, createdAt: true },
}),
prisma.blindBoxIdea.findMany({
where: { roomId, status: "drawn" },
orderBy: { createdAt: "desc" },
include: {
user: { select: { id: true, username: true, avatar: true } },
drawnBy: { select: { id: true, username: true, avatar: true } },
},
}),
]);
const idea = await prisma.blindBoxIdea.findUnique({ where: { id: ideaId } });
if (!idea) throw new ApiError("想法不存在", 404);
if (idea.userId !== userId) throw new ApiError("只能编辑自己的想法", 403);
if (idea.status !== "in_pool") throw new ApiError("已抽中的想法不能编辑");
return NextResponse.json({ poolCount, myIdeas, drawn });
} catch {
return errorResponse("查询失败", 500);
}
}
const updated = await prisma.blindBoxIdea.update({
where: { id: ideaId },
data: { content: content.trim() },
});
export async function PUT(req: NextRequest) {
try {
const { ideaId, userId, content } = await req.json();
return NextResponse.json({ id: updated.id, content: updated.content });
});
if (!userId) return errorResponse("请先登录", 401);
if (!ideaId) return errorResponse("缺少 ideaId", 400);
if (!content || typeof content !== "string" || content.trim().length === 0) {
return errorResponse("内容不能为空", 400);
}
if (content.trim().length > 200) {
return errorResponse("内容不能超过 200 字", 400);
}
export const DELETE = apiHandler(async (req) => {
const { ideaId, userId } = await req.json();
const idea = await prisma.blindBoxIdea.findUnique({ where: { id: ideaId } });
if (!idea) return errorResponse("想法不存在", 404);
if (idea.userId !== userId) return errorResponse("只能编辑自己的想法", 403);
if (idea.status !== "in_pool") return errorResponse("已抽中的想法不能编辑", 400);
if (!userId) throw new ApiError("请先登录", 401);
if (!ideaId) throw new ApiError("缺少 ideaId");
const updated = await prisma.blindBoxIdea.update({
where: { id: ideaId },
data: { content: content.trim() },
});
const idea = await prisma.blindBoxIdea.findUnique({ where: { id: ideaId } });
if (!idea) throw new ApiError("想法不存在", 404);
if (idea.userId !== userId) throw new ApiError("只能删除自己的想法", 403);
if (idea.status !== "in_pool") throw new ApiError("已抽中的想法不能删除");
return NextResponse.json({ id: updated.id, content: updated.content });
} catch {
return errorResponse("编辑失败", 500);
}
}
await prisma.blindBoxIdea.delete({ where: { id: ideaId } });
export async function DELETE(req: NextRequest) {
try {
const { ideaId, userId } = await req.json();
if (!userId) return errorResponse("请先登录", 401);
if (!ideaId) return errorResponse("缺少 ideaId", 400);
const idea = await prisma.blindBoxIdea.findUnique({ where: { id: ideaId } });
if (!idea) return errorResponse("想法不存在", 404);
if (idea.userId !== userId) return errorResponse("只能删除自己的想法", 403);
if (idea.status !== "in_pool") return errorResponse("已抽中的想法不能删除", 400);
await prisma.blindBoxIdea.delete({ where: { id: ideaId } });
return NextResponse.json({ deleted: true });
} catch {
return errorResponse("删除失败", 500);
}
}
return NextResponse.json({ deleted: true });
});