All quizzesMedium
Custom Providers — Series 3
Preview — 3 of 10 questions
What goes wrong here?
javascript
{
provide: 'REPORTER',
useFactory: (config: ConfigService, http: HttpService) => new Reporter(config, http),
inject: [HttpService, ConfigService], // ✗
}ANothing — Nest matches the dependencies by parameter type
BStartup fails, because inject must list the tokens alphabetically
Cinject is positional: the resolved values are passed to the factory in the order listed, so config receives the HttpService instance and http receives the ConfigService — and TypeScript cannot catch it, because the factory's parameter types are not checked against the array
DBoth dependencies resolve to undefined, since the order does not match
How does Nest sequence these?
javascript
const CONNECTION = Symbol('CONNECTION');
@Module({
providers: [
{ provide: CONNECTION, useFactory: (c: ConfigService) => createPool(c.get('DB_URL')), inject: [ConfigService] },
{ provide: 'CATS_REPO', useFactory: (pool: Pool) => new CatsRepository(pool), inject: [CONNECTION] },
],
})
export class CatsModule {}AIt resolves the dependency graph, so CONNECTION is created before the factory that injects it — declaration order in the array is irrelevant, and a custom token is an ordinary node in that graph
BIt runs the factories top to bottom, so reversing the array would break it
CCustom tokens cannot appear in another provider's inject array
DBoth factories run in parallel, and the second retries until the first completes
What does registering the SDK as a provider give you over importing and constructing it where it is used?
javascript
export const STRIPE = Symbol('STRIPE');
{
provide: STRIPE,
useFactory: (c: ConfigService) => new Stripe(c.getOrThrow('STRIPE_KEY'), { apiVersion: '2024-06-20' }),
inject: [ConfigService],
}AIt makes the SDK's network calls go through Nest's interceptor pipeline
BIt converts the SDK's callbacks into Observables
CIt guarantees the client is closed on shutdown
DOne configured instance, built from validated config and shared application-wide — and an injection point that tests can override, instead of each consumer constructing its own client from process.env
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.