nextjs-api-handler-utils
v1.0.0
Published
A utility package for creating Next.js API routes with built-in authentication, validation, and error handling.
Maintainers
Readme
Next.js API Handler
一个用于简化 Next.js (App Router) API 路由创建的工具包,提供认证、参数验证、错误处理等功能。
功能特性
- 🛡️ 基于 RBAC 的角色访问控制
- 📦 参数验证(基于 Zod)
- 🐛 统一错误处理
- 📝 标准化响应格式
- 🔧 可扩展的插件系统
- 🧪 完整的测试覆盖
- 🔄 支持多套权限系统
- 🎯 支持固定用户对象类型以获得更好的类型安全性
安装
npm install nextjs-api-handler快速开始
基础用法
import { createHandlerFactory } from "nextjs-api-handler";
import { z } from "zod";
// 创建处理器工厂
const createHandler = createHandlerFactory({
authFunction: async (request) => {
// 实现认证逻辑
return {
success: true as const,
user: {
id: "1",
roles: ["user"],
},
session: {
userId: "1",
},
};
},
});
const querySchema = z.object({
name: z.string().min(1),
});
export const GET = createHandler({
querySchema,
handler: async ({ query }) => {
return {
message: `Hello, ${query.name}!`,
};
},
});认证处理
import { createHandlerFactory } from "nextjs-api-handler";
// 创建处理器工厂
const createHandler = createHandlerFactory({
authFunction: async (request) => {
// 实现认证逻辑
return {
success: true as const,
user: {
id: "1",
roles: ["member", "admin"],
},
session: {
userId: "1",
},
};
},
});
export const GET = createHandler({
auth: ["member", "admin"],
handler: async ({ user }) => {
return {
userId: user.id,
roles: user.roles,
};
},
});角色授权
import { createHandlerFactory } from "nextjs-api-handler";
// 创建处理器工厂
const createHandler = createHandlerFactory({
authFunction: async (request) => {
// 实现认证逻辑
return {
success: true as const,
user: {
id: "1",
roles: ["admin"],
},
session: {
userId: "1",
},
};
},
});
export const DELETE = createHandler({
auth: ["admin"],
handler: async ({ user }) => {
return {
message: `Hello, ${user.roles[0]}!`,
};
},
});参数验证
import { createHandlerFactory } from "nextjs-api-handler";
import { z } from "zod";
// 创建处理器工厂
const createHandler = createHandlerFactory({
authFunction: async (request) => {
// 实现认证逻辑
return {
success: true as const,
user: {
id: "1",
roles: ["member"],
},
session: {
userId: "1",
},
};
},
});
const bodySchema = z.object({
email: z.string().email(),
age: z.number().min(18),
});
export const POST = createHandler({
auth: ["member"],
bodySchema,
handler: async ({ body, user }) => {
// body 已经被验证并类型化
return {
message: `User ${body.email} is ${body.age} years old`,
roles: user.roles,
};
},
});固定用户对象类型
通过使用泛型参数,您可以固定用户对象的类型以获得更好的类型安全性:
import { createHandlerFactory } from "nextjs-api-handler";
import { AuthFunction, User } from "nextjs-api-handler";
// 定义角色类型
type UserRole = "admin" | "user" | "guest";
// 定义扩展的用户接口,固定用户对象的类型
interface ApplicationUser extends User<UserRole> {
id: string;
name: string;
email: string;
department: string;
createdAt: Date;
}
// 模拟认证函数,返回固定类型的用户对象
const applicationAuthFunction: AuthFunction<UserRole, ApplicationUser> = async (
request
) => {
// 这里应该实现实际的认证逻辑
// 例如从 JWT token 或 session 中提取用户信息
return {
success: true as const,
user: {
id: "1",
name: "John Doe",
email: "[email protected]",
department: "Engineering",
createdAt: new Date(),
roles: ["admin"],
},
session: {
userId: "1",
// 可以包含其他会话信息
},
};
};
// 创建带有固定用户对象类型的处理器工厂
// 现在 TUser 被固定为 ApplicationUser 类型
const createAppHandler = createHandlerFactory<UserRole, ApplicationUser>({
authFunction: applicationAuthFunction,
});
// 管理员专用的处理器
const adminHandler = createAppHandler({
auth: "admin",
handler: async ({ user }) => {
// 在这里,user 参数现在有完整的类型信息
// TypeScript 能够正确识别所有属性的类型
// user.id, user.name, user.email, user.department 都有正确的类型
console.log(`Admin User: ${user.name} from ${user.department}`);
// user.roles 也有正确的类型
console.log(`Roles: ${user.roles.join(", ")}`);
// user.createdAt 也是正确的 Date 类型
console.log(`User since: ${user.createdAt.toISOString()}`);
// 返回类型也会被正确推断
return {
message: `Hello, ${user.name}!`,
userId: user.id,
department: user.department,
isAdmin: user.roles.includes("admin"),
};
},
});多套权限系统支持
在同一个项目中使用多套权限系统,例如后台管理系统和客户端(H5/小程序)使用不同的认证机制:
import { createHandlerFactory } from "nextjs-api-handler";
// 定义角色类型
type UserRole = "admin" | "user" | "guest";
// 定义扩展的用户接口
interface ApplicationUser extends User<UserRole> {
id: string;
name: string;
email: string;
department: string;
}
// 创建后台管理权限系统
const adminAuthFunction = async (request) => {
// 实现后台管理系统的认证逻辑
return {
success: true as const,
user: {
id: "1",
name: "Admin User",
email: "[email protected]",
department: "IT",
roles: ["admin"],
},
session: {
userId: "1",
},
};
};
// 创建客户端权限系统
const clientAuthFunction = async (request) => {
// 实现客户端的认证逻辑
return {
success: true as const,
user: {
id: "2",
name: "Client User",
email: "[email protected]",
department: "Sales",
roles: ["user"],
},
session: {
userId: "2",
},
};
};
// 创建带有固定用户对象类型的处理器工厂
const adminHandlerFactory = createHandlerFactory<UserRole, ApplicationUser>({
authFunction: adminAuthFunction,
});
const clientHandlerFactory = createHandlerFactory<UserRole, ApplicationUser>({
authFunction: clientAuthFunction,
});
// 使用不同的权限系统创建API处理器
export const adminApi = adminHandlerFactory({
auth: ["admin"],
handler: async ({ user }) => {
// 现在 user 对象具有完整的类型信息
// user.name, user.email, user.department 都有正确的类型
return {
message: `Hello, ${user.name} from ${user.department}!`,
role: user.roles[0],
};
},
});
export const clientApi = clientHandlerFactory({
auth: ["user"],
handler: async ({ user }) => {
// 同样,user 对象具有完整的类型信息
return {
message: `Hello, ${user.name} from ${user.department}!`,
role: user.roles[0],
};
},
});API 参考
createHandlerFactory<TRole, TUser>(config)
创建一个自定义配置的处理器工厂函数,支持多套权限系统和固定用户对象类型。
泛型参数:
TRole(可选): 角色类型,默认为 stringTUser(可选): 用户对象类型,默认为 User
参数:
config: 配置对象authFunction(必需): 自定义认证函数(接收 NextRequest 参数,返回 Promise)
返回值:
一个创建 API 处理器的工厂函数。
响应格式
所有响应都遵循统一的格式:
interface ApiResponse<T> {
code: number; // 0 表示成功,其他值表示错误
message: string; // 响应消息
data: T; // 响应数据
}错误处理
包内包含统一的错误处理机制。自定义错误可以通过抛出 AppError 实例来实现:
import { AppError } from "nextjs-api-handler";
// 在处理器中抛出错误
throw new AppError("Custom error message", 400, "CUSTOM_ERROR_CODE");许可证
MIT
