API Reference

wrapAction API

TL;DR (One Sentence)

wrapAction(actionName, handler, options?): Automatically completes authentication, admin permissions, and RBAC checks based on naming conventions, and logs operations.


๐Ÿ‘€ Quick Start

import { wrapAction } from '@/lib/core/action-wrapper'

// Public Interface (No Login Required)
export const pubGetSiteConfig = wrapAction('pubGetSiteConfig', async () => {
  return { success: true, data: { name: 'NextJS Base' } }
})

// Available After Login
export const authGetProfile = wrapAction('authGetProfile', async (_, ctx) => {
  return { success: true, data: { userId: ctx.userId } }
})

// Admin Permission + RBAC Check (sys*)
export const sysGetUserList = wrapAction('sysGetUserList', async (params, ctx) => {
  // Admin access and action permission checks completed
  return { success: true, data: [] }
})

๐Ÿ”ค Naming Conventions (Determines Permission Level)

PrefixLevelAuthRBACLog
pubPUBLICโŒโŒโœ…
authAUTHโœ…โŒโœ…
sysSYSTEMโœ…โœ…โœ…
_PRIVATE---

You can also force specify the level via the third parameter options.level (not commonly used).


โš™๏ธ Signature

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>

Parameter Description:

  • actionName: Used for permission parsing and log recording (must include prefix).
  • handler: Your business function, second parameter ctx already contains userId/isAdmin/user.
  • options.skipLog: Whether to skip operation logs (default false).
  • options.level: Force specify permission level.

๐Ÿ” Behavior Details

  • sys*:
    • Check if logged in;
    • Check if has admin access permission;
    • Execute RBAC action permission matching (based on actionName);
    • Unified error return { success:false, error }, and log.
  • auth*: Only requires login;
  • pub*: Can be accessed anonymously, will try to parse session but not enforce.
  • _: Private function, directly rejects frontend calls.

๐Ÿงช Best Practices

  • Action names must include prefix: pub/auth/sys/_;
  • Use single parameter as input structure: For update/delete, recommend { id, ...data };
  • Business errors throw new Error('message') and frontend will receive friendly prompt.