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,27 +1,21 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { apiHandler, ApiError } from "@/lib/api";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
export const POST = apiHandler(async (req) => {
|
||||
const { username, password, avatar } = await req.json();
|
||||
|
||||
if (!username || !password) {
|
||||
return NextResponse.json({ error: "用户名和密码为必填项" }, { status: 400 });
|
||||
}
|
||||
if (!username || !password) throw new ApiError("用户名和密码为必填项");
|
||||
|
||||
const trimmedUsername = username.trim();
|
||||
if (trimmedUsername.length < 2 || trimmedUsername.length > 16) {
|
||||
return NextResponse.json({ error: "用户名需要 2-16 个字符" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return NextResponse.json({ error: "密码至少 6 个字符" }, { status: 400 });
|
||||
throw new ApiError("用户名需要 2-16 个字符");
|
||||
}
|
||||
if (password.length < 6) throw new ApiError("密码至少 6 个字符");
|
||||
|
||||
const existing = await prisma.user.findUnique({ where: { username: trimmedUsername } });
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: "用户名已被注册" }, { status: 409 });
|
||||
}
|
||||
if (existing) throw new ApiError("用户名已被注册", 409);
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
@@ -38,4 +32,4 @@ export async function POST(req: NextRequest) {
|
||||
username: user.username,
|
||||
avatar: user.avatar,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user