Search code examples
typescriptnestjsdecorator

using nestjs providers inside a custom function


i'm using nestjs and created a custom decorator which is not a nestjs decorator and add the descriptor.value which is the method into an array of objects along with some other info the problem is the method comes from inside a nestjs class that has it's own injected providers but this decorator just takes the method and store it so it can be used somewhere else the problem is when i try to use the function, the nestjs injected functions are not available at that scope and are undefined. what can be done? thanks

i tried creating a bound function with target Object but there was no luck in that


Solution

  • okay so i figured it out and it was so simple, in order to have nestjs class context you need to bind the class context to the decorated function, if you do it on your decorator it won't work since typescript execute those functions when the app start but nest is not yet initialized so even if you pass your class ref, it's either undefined or an empty class, in order to fix this you have to do the following:

    1. set metadata on your decorator using Reflector
    2. on create an app.service.ts
    3. use nestjs Discovery Module (better to use golevelup version)
    4. do a on module init implementation and get those functions with their meta
    5. now get the handler which is the method and bind the parent class instance it it
    6. you are all set