Custom Providers — Series 2

Preview — 3 of 10 questions

What does using a Symbol buy you over provide: 'CONNECTION'?

javascript
export const CONNECTION = Symbol('CONNECTION');

@Module({ providers: [{ provide: CONNECTION, useFactory: createConnection }] })
export class DatabaseModule {}
ASymbols let Nest resolve the provider without @Inject() at the injection site
BSymbols make the provider automatically global
CA Symbol is unique by identity, so two libraries that both happen to pick the name CONNECTION cannot collide — whereas equal strings are the same token
DSymbols are required for any provider created with useFactory

Why is an abstract class often preferred over a string token here?

javascript
export abstract class PaymentGateway {
  abstract charge(amount: number): Promise<void>;
}

@Module({
  providers: [{ provide: PaymentGateway, useClass: StripeGateway }],
  exports: [PaymentGateway],
})
export class PaymentModule {}

constructor(private readonly gateway: PaymentGateway) {} // no @Inject needed
ABecause abstract classes can hold state that interfaces cannot
BBecause useClass only accepts abstract classes as its token
CBecause Nest instantiates the abstract class itself if the implementation fails to load
DBecause an abstract class survives compilation as a real runtime value, so it works as a token and as the parameter's type — giving type-checked injection without @Inject()

What does the object form in inject do?

javascript
{
  provide: 'MAILER',
  useFactory: (config: ConfigService, tracer?: TracerService) =>
    new Mailer(config.get('SMTP_URL'), tracer),
  inject: [ConfigService, { token: TracerService, optional: true }],
}
AIt marks that dependency optional: if TracerService is not registered, the factory receives undefined instead of the application failing to start
BIt defers resolution of TracerService until the first time the factory's result is used
CIt instructs Nest to create a new TracerService instance exclusively for this factory
DIt documents the dependency for tooling but has no runtime effect

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.