API 参考
wrapAction API
TL;DR(一句话)
wrapAction(actionName, handler, options?):按命名约定自动完成认证、后台权限与 RBAC 检查,并记录操作日志。
👀 快速上手
import { wrapAction } from '@/lib/core/action-wrapper'
// 公开接口(无需登录)
export const pubGetSiteConfig = wrapAction('pubGetSiteConfig', async () => {
return { success: true, data: { name: 'NextJS Base' } }
})
// 登录后可用
export const authGetProfile = wrapAction('authGetProfile', async (_, ctx) => {
return { success: true, data: { userId: ctx.userId } }
})
// 后台权限 + RBAC 检查(sys*)
export const sysGetUserList = wrapAction('sysGetUserList', async (params, ctx) => {
// 已完成后台访问与动作权限校验
return { success: true, data: [] }
})🔤 命名约定(决定权限级别)
| 前缀 | 级别 | 认证 | RBAC | 日志 |
|---|---|---|---|---|
pub | PUBLIC | ❌ | ❌ | ✅ |
auth | AUTH | ✅ | ❌ | ✅ |
sys | SYSTEM | ✅ | ✅ | ✅ |
_ | PRIVATE | - | - | - |
也可以通过第三个参数
options.level强制指定等级(不常用)。
⚙️ 签名
wrapAction(
actionName: string,
handler: (params: any, ctx: { userId: string|null, isAdmin: boolean, user?: any }) => Promise<any>,
options?: { skipLog?: boolean, level?: 'public'|'auth'|'system'|'private' }
): (...args:any[]) => Promise<any>参数说明:
- actionName:用于权限解析、日志记录(务必带前缀)。
- handler:你的业务函数,第二个参数
ctx已包含userId/isAdmin/user。 - options.skipLog:是否跳过操作日志(默认 false)。
- options.level:强制指定权限等级。
🔐 行为细节
- sys*:
- 检查是否已登录;
- 检查是否有后台访问权限;
- 执行 RBAC 动作权限匹配(基于 actionName);
- 统一错误返回
{ success:false, error },并记录日志。
- auth*:仅要求登录;
- pub*:可匿名访问,会尝试解析会话但不强制。
_:私有函数,直接拒绝前端调用。
🧪 最佳实践
- Action 名务必带前缀:
pub/auth/sys/_; - 使用单参数作为输入结构:更新/删除等推荐
{ id, ...data }; - 业务错误抛出
new Error('消息')即可,前端会收到友好提示。