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!

0 Answers