M
M
Movsar-Khalakhoev2021-10-09 10:40:32
typescript
Movsar-Khalakhoev, 2021-10-09 10:40:32

How to set a decorator on a method that is not an endpoint?

Hello!

Question on NestJS.
The task is to make sure that when the controller's secondMethod method is called from the firstMethod method, a custom decorator is triggered. At the moment this is not happening. I noticed that only those decorators that are hung on endpoints work, that is, on methods that are marked with Get, Post, Patch, etc. decorators.

class Controller {
      
      @Get('/')
      firstMethod() {
        secondMethod()
      }
      
      @CustomDecorator()
      secondMethod() {}
    }


I've attached a minimal version of the code. CustomDecorator not working.

Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Sviridov, 2021-10-09
@Movsar-Khalakhoev

Here's how to make a decorator - it will work:

const CustomDecorator = () => (target: Object, propertyKey: string, descriptor: PropertyDescriptor) => {
  let sourceMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log("before");
    let result = sourceMethod.apply(this, args);
    console.log("after");
    return result;
  }
}

PS here you can read more details

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question