NestJS运行时如何全局扫描获取所有装饰器的值并存储到数据库
实现方案
第一步:确保自定义装饰器正确设置元数据
首先你的@HashPermission装饰器需要用Nest提供的SetMetadata绑定元数据,示例写法:
import { SetMetadata } from '@nestjs/common'; // 全局统一的元数据key,避免拼写错误 export const HASH_PERMISSION_KEY = 'hash_permission'; export const HashPermission = (accessValue: string) => SetMetadata(HASH_PERMISSION_KEY, accessValue);
第二步:在bootstrap启动阶段遍历所有路由收集元数据
你拿不到context.getHandler()是因为ExecutionContext只有请求触发时才会生成,启动阶段没有请求上下文,直接遍历所有模块的控制器和路由方法即可拿到所有装饰器值,修改后的bootstrap代码:
import { Reflector } from '@nestjs/core'; import { HASH_PERMISSION_KEY } from './common/decorators/hash-permission.decorator'; // 引入你自己实现的权限存储服务 import { PermissionService } from './permission/permission.service'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe()); // 存储逻辑实现 const reflector = app.get(Reflector); const permissionService = app.get(PermissionService); // 获取所有已注册的模块 const modules = app.getModules(); for (const module of modules) { // 遍历模块下所有控制器 for (const controller of module.controllers) { const ControllerClazz = controller.metatype; // 先取控制器类上的装饰器值(如果你的装饰器支持加在类上) const controllerPermission = reflector.get<string>(HASH_PERMISSION_KEY, ControllerClazz); if (controllerPermission) { // 调用服务存入数据库,建议加去重逻辑避免重复插入 await permissionService.upsertPermission(controllerPermission); } // 遍历控制器下所有路由方法 const methodNames = Object.getOwnPropertyNames(ControllerClazz.prototype) .filter(name => name !== 'constructor' && typeof ControllerClazz.prototype[name] === 'function'); for (const methodName of methodNames) { const routeMethod = ControllerClazz.prototype[methodName]; const methodPermission = reflector.get<string>(HASH_PERMISSION_KEY, routeMethod); if (methodPermission) { await permissionService.upsertPermission(methodPermission); } } } } await app.listen(3000); } bootstrap();
注意事项
- 你的
PermissionService需要在全局模块(比如AppModule)中声明并导出,保证app.get()可以获取到实例 - 存储权限的方法建议做唯一键校验,比如给权限值字段加唯一索引,或者存入前先查询是否存在,避免每次启动重复插入
- 如果项目中用到了懒加载模块,上述遍历逻辑无法拿到未加载的模块数据,可以在懒加载模块中实现
OnModuleInit生命周期钩子,在钩子中执行当前模块的控制器遍历逻辑即可
内容的提问来源于stack exchange,提问作者Izweb Technologies
相关产品推荐
相关产品推荐

