我正在为 NestJS 编写一个模块,我想在其中自定义ClassDecorator
:
- 上课
@Injectable
- 在类实例中注入依赖项
这是几行代码,说明了我的期望:
// app.module.ts
@Module({
providers: [AppService, MyClass]
})
export class AppModule {}
// my-class.ts
@MyClassDecorator(AppService)
export class MyClass {}
// Somewhere else where MyClass is injected as `myclass`
console.log(myclass)
// MyClass { injectedThroughDecorator: AppService {} }
我在谷歌上搜索了很多关于如何实现自定义装饰器的参考资料,我认为我对此很满意。我也开始阅读一些文档,reflect-metadata
因为我认为反射可以帮助我实现这一目标。
下一步是定义一个方法装饰器,它可以访问AppService
注入的实例MyClassDecorator
。
例如,假设它AppService
被实现为EventEmitter
:
@MyClassDecorator(AppService)
export class MyClass {
@MyMethodDecorator('event')
myDecoratedFunction(eventName: string, data: any) {
console.log(`Hi there! I've been triggered by the AppService's ${eventName} event with ${data}`);
}
}
你对我应该如何实现这样的装饰器有什么建议吗?任何帮助/示例/参考将不胜感激。最后,不要犹豫,询问更多细节或解释我想要实现的目标。
感谢您阅读我,祝您有美好的一天!