根据UI层调用需求,这里提供更适用的高阶函数实现方案:

// 在文件顶部新增权限校验工具函数
export const withAPIAuth = (permissionCode) => async (apiCall) => {
  // 获取权限状态(示例使用伪代码,需替换为实际权限获取逻辑)
  const hasPermission = await checkUserPermission(permissionCode);
  
  if (!hasPermission) {
    throw new Error(`Missing permission: ${permissionCode}`);
    // 或返回空数据避免阻塞流程:return { code: 403 }
  }
  
  try {
    return await apiCall();
  } catch (error) {
    console.error('API调用失败:', error);
    throw error;
  }
};
 
// 在UI组件中的使用示例(伪代码):
/*
import { getDepartmentTree, withAPIAuth } from '@/api/org';
 
// 带权限校验的调用
const fetchDepartment = async () => {
  try {
    const res = await withAPIAuth('DEPARTMENT_READ')(() => getDepartmentTree());
    // 处理响应数据
  } catch (error) {
    if (error.message.includes('Missing permission')) {
      message.error('无权限访问部门数据');
    }
  }
}
*/

实现改进说明:

  1. 调用方式更灵活
    支持在UI层按需包裹任意API调用:
// 基本调用
getDepartmentTree(); 
 
// 带权限校验的调用
withAPIAuth('PERM_CODE')(() => getDepartmentTree(param));
  1. 权限校验逻辑解耦
    建议在项目中单独创建权限校验模块:
// 权限校验核心逻辑(示例)
async function checkUserPermission(code) {
  // 从Redux/Vuex获取权限列表
  const { permissions } = store.getState().user;
  // 或调用权限校验接口
  // const res = await checkPermissionAPI(code); 
  return permissions?.includes(code);
}
  1. 组合式调用支持
    可组合多个权限校验:
withAPIAuth('PERM_1')(() => 
  withAPIAuth('PERM_2')(() => 
    getDepartmentTree()
  )
);
  1. TypeScript支持建议
    如果项目使用TS,可添加类型声明:
type AuthAPICall<T> = () => Promise<T>;
 
function withAPIAuth<T>(code: string): (apiCall: AuthAPICall<T>) => Promise<T>;

我明白您的需求,这里提供更优雅的实现方案:

// 在文件顶部新增 (保留原有导入)
export const withAPIAuth = (...permissionCodes) => async (apiCall) => {
  // 统一检查多个权限
  const hasPermissions = await Promise.all(
    permissionCodes.map(code => checkUserPermission(code))
  );
  
  if (hasPermissions.some(valid => !valid)) {
    throw new Error(`Missing permissions: ${permissionCodes.join(', ')}`);
  }
  
  return apiCall();
};
 
// 使用示例 (单行调用)
withAPIAuth('PERM_1', 'PERM_2')(() => getDepartmentTree());

改进说明:

  1. 参数扁平化:使用剩余参数语法 ...permissionCodes 支持多个权限码
  2. 并行校验:通过 Promise.all 并行校验多个权限
  3. 统一错误处理:合并权限错误提示,避免多次提示
  4. TS类型支持(可选):可添加类型声明支持任意参数数量

嵌套改造成果对比:

// 改造前
withAPIAuth('PERM_1')(() => 
  withAPIAuth('PERM_2')(() => 
    getDepartmentTree()
  )
);
 
// 改造后
withAPIAuth('PERM_1', 'PERM_2')(() => getDepartmentTree());