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
+13 -22
View File
@@ -1,11 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { apiHandler, ApiError } from "@/lib/api";
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 favorites = await prisma.favorite.findMany({
where: { userId },
@@ -20,19 +19,15 @@ export async function GET(req: NextRequest) {
createdAt: f.createdAt.toISOString(),
})),
);
}
});
export async function POST(req: NextRequest) {
export const POST = apiHandler(async (req) => {
const { userId, restaurant } = await req.json();
if (!userId || !restaurant) {
return NextResponse.json({ error: "缺少必要字段" }, { status: 400 });
}
if (!userId || !restaurant) 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.favorite.findFirst({
where: {
@@ -53,20 +48,16 @@ export async function POST(req: NextRequest) {
});
return NextResponse.json({ id: fav.id });
}
});
export async function DELETE(req: NextRequest) {
export const DELETE = apiHandler(async (req) => {
const { userId, favoriteId } = await req.json();
if (!userId || !favoriteId) {
return NextResponse.json({ error: "缺少必要字段" }, { status: 400 });
}
if (!userId || !favoriteId) throw new ApiError("缺少必要字段");
const fav = await prisma.favorite.findUnique({ where: { id: favoriteId } });
if (!fav || fav.userId !== userId) {
return NextResponse.json({ error: "收藏不存在" }, { status: 404 });
}
if (!fav || fav.userId !== userId) throw new ApiError("收藏不存在", 404);
await prisma.favorite.delete({ where: { id: favoriteId } });
return NextResponse.json({ ok: true });
}
});