Class decorator Nestjs modify each method in a class

Viewed 201

I want to create a decorator that would get all methods of a class and wrap them with certain functionality, for this example, just logging like this:

export function CustDec<T extends new (...args: any[]) => any>(Target: T) {
  return class extends Target {
    constructor(...args: any[]) {
      super(...args);
      console.log('@--------------------@');
      (Target as any).prototype.alphaMethod = async (args: any[]) => {
        console.log('@-before-@');
        await (Target as any).alphaMethod();
        console.log('@-after-@');
      };
    }
  };
}

The problem is when I apply this decorator to my class:

import { Controller, Post } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Firewall } from 'src/auth/decorators/firewall.decorator';
import { CustDec } from './feedback.decorator';

@CustDec
@ApiTags('feedback')
@Controller('feedback')
export class FeedbackController {
  constructor() {
    setTimeout(async () => {
      await this.alphaMethod(); // <--- here
    }, 3000);
  }

  @Firewall()
  @Post('')
  async alphaMethod() { // <-- and here
    return 'some promised result';
  }
}

When I try to call /feedback endpoint on my controller, I get an error as if Firewall and Post decorators stopped working after my CustDec changed alphaMethod. And even if I call alphaMethod from inside my FeedbackController constructor method, I get another error:

@-before-@
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
TypeError: Target.alphaMethod is not a function
    at FeedbackController.Target.alphaMethod (/home/zagrava/workspace/test-nest/backend/src/feedback/feedback.decorator.ts:8:31)
    at Timeout._onTimeout (/home/zagrava/workspace/test-nest/backend/src/feedback/feedback.controller.ts:12:18)
    at listOnTimeout (node:internal/timers:564:17)
    at processTimers (node:internal/timers:507:7)

How do I make my CustDec properly wrap all methods of a class with logging?

1 Answers

A class decorator can be implemented like below :

function intercept<T extends { new(...args: any[]): {} }>(target: T) {
  const methods = getMethods(target.prototype);
  for (const method of methods) {
    const currentMethod = target.prototype[method]
    target.prototype[method] = async (...args: any[]) => {
      console.log("intercepted", new Date());
      const result = currentMethod(args)
      if (result instanceof Promise) {
        await result
      }
      console.log("executed", new Date());
      return result;
    }
  }
}

The idea is to get all the functions of the class (except the constructor itself) and wrap them within your custom-defined function. A helper method to get functions of a class like the below is useful for this scenario :

const getMethods = (obj: any) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function' && item !== "constructor")

Playground

Multiple decorators in action

Related