0

I'm writing a module for NestJS where I'd like to have a custom ClassDecorator that:

  • Makes a class @Injectable
  • Injects a dependency in the class instance

Here is a few lines of code that illustrate what I expect:

// 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 {} }

I've googled for a lot of reference on how to implement custom decorators and I think I'm good with this. I've also started to read some documentations about reflect-metadata as I think reflection could help me achieve this.

The next step is to define a method decorator that would have access to the AppService instance injected with MyClassDecorator.

For example, let's say that AppService is implemented as an 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}`);
    }

}

Do you have any advice on how I should implement such a decorator? Any help/example/reference would be greatly appreciated. Lastly, don't hesitate to ask for more details or explanation on what I'm trying to achieve.

Thanks for reading me, Have a nice day!

fwoelffel
  • 412
  • 7
  • 16
  • Not clear how `myDecoratedFunction` is going to be invoked and how that relates to `AppService`. Can you give a little more context? A more concrete and complete example would help. – Andrew Eisenberg May 20 '19 at 00:39
  • Thanks @AndrewEisenberg for commenting on this question. I've found a solution but I haven't answered yet. The point was to perform something like `myAppServiceInstance.on('event', myClassInstance.myDecoratedFunction)` You can see how I implemented this here https://github.com/fwoelffel/nest-bull/blob/dev/lib/bull.explorer.ts – fwoelffel May 20 '19 at 09:30

0 Answers0