Search code examples
typescriptservicedecoratornestjs

Nestjs: avoid repetitive expression in constructor of service


In NestJs I have this constructor :

@Injectable()
export class DummyService {
  constructor(
    private readonly logger: LoggerService,
    private readonly config: ConfigService,
    private readonly session: SessionService,
    private readonly core: CoreService,
    private readonly tracking: TrackingService,
  ) {
    this.logger.setContext(this.constructor.name);
  }

}

this line :
this.logger.setContext(this.constructor.name); ... is boring me because every service required it.

I'd like to add a Decorator (@LogContext()) or ... something else to avoid this line. Something like :

@LogContext(LoggerService)
@Injectable()
export class DummyService {
  constructor(
    private readonly config: ConfigService,
    private readonly session: SessionService,
    private readonly core: CoreService,
    private readonly tracking: TrackingService,
  ) {}
}

But I don't know how to do it. Note: It's impossible to do it by inheritance, Dependency Injection rejects inheritance.


Solution

  • You can technically do inheritance with dependency injection, in this case it won't change too much. What I've done in a custom logger is create a LoggerModule.forFeature(FeatureClass.name) where I create a new injection token and then use @InjectLogger(FeatureClass.name) to inject the specified logger. This allows for less duplications in code (though technically the meta is still duplicating itself).

    The logger package I'm talking about specifically is Ogma and I made sure I was developing it with Nest's DI system in mind.