Access an injected service from within a Class decorator? Typescript / NestJS

Viewed 1240

Is it possible to access an injected service from within a Class decorator?

I want to get the service within the custom constructor:

function CustDec(constructor: Function) {
  var original = constructor;

  var f: any = function (...args) {
    // I want to get injectedService here. How?
    // I've tried things like this.injectedService but that doesn't work
    return new original(...args);
  }

  f.prototype = target.prototype;
  return f;
}

@CustDec
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,
  ) {}
}
1 Answers

Based on the official class-decorator docs, here's a way that should work:

function CustDec<T extends new(...args: any[]) => {}>(Target: T) {
    return class extends Target {
        constructor(...args: any[]) {
            super(...args);
            (args[0] as InjectedService).doSomething();
        }
    }
}

@CustDec
@Injectable()
class MyService {
  constructor(
    private readonly injectedService: InjectedService,
  ) {}
}

I've also created an example on TS-Playground.

Related