nest装饰器可以说是核心的内容,整套逻辑都是通过装饰器实现的。
核心是reflect的metadata api
/**
* metadataKey 唯一key
* metadataValue 值
* target 目标类
* propertyKey 目标属性名
*/
Reflect.defineMetadata(metadataKey, metadataValue, target);
Reflect.defineMetadata(metadataKey, metadataValue, target, propertyKey);
let result = Reflect.getMetadata(metadataKey, target);
let result = Reflect.getMetadata(metadataKey, target, propertyKey);几个核心的东西
- reflect-metadata库提供反射元数据api,使得通过装饰器能给类添加元数据,得到依赖关系
- typescript提供编译时生成元数据的能力(emitDecoratorMetadata,experimentalDecorators),使得能自动生成额外的元数据,其中key值分别有design:type,design:paramtypes,design:returntype,从而获取构造器的参数类型
所以得出扫描依赖和依赖注入的原理就是,通过装饰器给class添加metadata,在由typescript自动添加类型相关的metadata,初始化时,根据这些元数据进行实例的创建
nest提供了SetMetadata装饰器,让我们能够给class和method设置一些自定义的metadata,使用是只能在Guard和Interceptor里面通过注入Reflector的方式获取,因为这两个里面能拿到上下文,从而能获取到具体的方法或者class
@SetMetadata('roles', ['admin'])
this.reflector.get('roles', context.getHandler())