Custom providers

In earlier chapters, we touched on various aspects of Dependency Injection (DI) and how it is used in Nest. One example of this is the constructor based dependency injection used to inject instances (often service providers) into classes. You won’t be surprised to learn that Dependency Injection is built in to the Nest core in a fundamental way. So far, we’ve only explored one main pattern. As your application grows more complex, you may need to take advantage of the full features of the DI system, so let’s explore them in more detail.

DI fundamentals

Dependency injection is an inversion of control (IoC) technique wherein you delegate instantiation of dependencies to the IoC container (in our case, the NestJS runtime system), instead of doing it in your own code imperatively. Let’s examine what’s happening in this example from the Providers chapter.

First, we define a provider. The @Injectable() decorator marks the CatsService class as a provider.

cats.service.ts

  1. import { Injectable } from '@nestjs/common';
  2. import { Cat } from './interfaces/cat.interface';
  3. @Injectable()
  4. export class CatsService {
  5. private readonly cats: Cat[] = [];
  6. findAll(): Cat[] {
  7. return this.cats;
  8. }
  9. }
  1. import { Injectable } from '@nestjs/common';
  2. @Injectable()
  3. export class CatsService {
  4. constructor() {
  5. this.cats = [];
  6. }
  7. findAll() {
  8. return this.cats;
  9. }
  10. }

Then we request that Nest inject the provider into our controller class:

cats.controller.ts

  1. import { Controller, Get } from '@nestjs/common';
  2. import { CatsService } from './cats.service';
  3. import { Cat } from './interfaces/cat.interface';
  4. @Controller('cats')
  5. export class CatsController {
  6. constructor(private catsService: CatsService) {}
  7. @Get()
  8. async findAll(): Promise<Cat[]> {
  9. return this.catsService.findAll();
  10. }
  11. }
  1. import { Controller, Get, Bind, Dependencies } from '@nestjs/common';
  2. import { CatsService } from './cats.service';
  3. @Controller('cats')
  4. @Dependencies(CatsService)
  5. export class CatsController {
  6. constructor(catsService) {
  7. this.catsService = catsService;
  8. }
  9. @Get()
  10. async findAll() {
  11. return this.catsService.findAll();
  12. }
  13. }

Finally, we register the provider with the Nest IoC container:

app.module.ts

  1. import { Module } from '@nestjs/common';
  2. import { CatsController } from './cats/cats.controller';
  3. import { CatsService } from './cats/cats.service';
  4. @Module({
  5. controllers: [CatsController],
  6. providers: [CatsService],
  7. })
  8. export class AppModule {}

What exactly is happening under the covers to make this work? There are three key steps in the process:

  1. In cats.service.ts, the @Injectable() decorator declares the CatsService class as a class that can be managed by the Nest IoC container.

  2. In cats.controller.ts, CatsController declares a dependency on the CatsService token with constructor injection:

  1. constructor(private catsService: CatsService)
  1. In app.module.ts, we associate the token CatsService with the class CatsService from the cats.service.ts file. We’ll see below exactly how this association (also called registration) occurs.

When the Nest IoC container instantiates a CatsController, it first looks for any dependencies*. When it finds the CatsService dependency, it performs a lookup on the CatsService token, which returns the CatsService class, per the registration step (#3 above). Assuming SINGLETON scope (the default behavior), Nest will then either create an instance of CatsService, cache it, and return it, or if one is already cached, return the existing instance.

*This explanation is a bit simplified to illustrate the point. One important area we glossed over is that the process of analyzing the code for dependencies is very sophisticated, and happens during application bootstrapping. One key feature is that dependency analysis (or “creating the dependency graph”), is transitive. In the above example, if the CatsService itself had dependencies, those too would be resolved. The dependency graph ensures that dependencies are resolved in the correct order - essentially “bottom up”. This mechanism relieves the developer from having to manage such complex dependency graphs.

Learn the right way!

  • Custom providers - 图1 60+ chapters
  • Custom providers - 图2 4+ hours of videos
  • Custom providers - 图3 Official certificate
  • Custom providers - 图4 Deep-dive sessions

Explore official courses

Standard providers

Let’s take a closer look at the @Module() decorator. In app.module, we declare:

  1. @Module({
  2. controllers: [CatsController],
  3. providers: [CatsService],
  4. })

The providers property takes an array of providers. So far, we’ve supplied those providers via a list of class names. In fact, the syntax providers: [CatsService] is short-hand for the more complete syntax:

  1. providers: [
  2. {
  3. provide: CatsService,
  4. useClass: CatsService,
  5. },
  6. ];

Now that we see this explicit construction, we can understand the registration process. Here, we are clearly associating the token CatsService with the class CatsService. The short-hand notation is merely a convenience to simplify the most common use-case, where the token is used to request an instance of a class by the same name.

Custom providers

What happens when your requirements go beyond those offered by Standard providers? Here are a few examples:

  • You want to create a custom instance instead of having Nest instantiate (or return a cached instance of) a class
  • You want to re-use an existing class in a second dependency
  • You want to override a class with a mock version for testing

Nest allows you to define Custom providers to handle these cases. It provides several ways to define custom providers. Let’s walk through them.

Value providers: useValue

The useValue syntax is useful for injecting a constant value, putting an external library into the Nest container, or replacing a real implementation with a mock object. Let’s say you’d like to force Nest to use a mock CatsService for testing purposes.

  1. import { CatsService } from './cats.service';
  2. const mockCatsService = {
  3. /* mock implementation
  4. ...
  5. */
  6. };
  7. @Module({
  8. imports: [CatsModule],
  9. providers: [
  10. {
  11. provide: CatsService,
  12. useValue: mockCatsService,
  13. },
  14. ],
  15. })
  16. export class AppModule {}

In this example, the CatsService token will resolve to the mockCatsService mock object. useValue requires a value - in this case a literal object that has the same interface as the CatsService class it is replacing. Because of TypeScript’s structural typing, you can use any object that has a compatible interface, including a literal object or a class instance instantiated with new.

Non-class-based provider tokens

So far, we’ve used class names as our provider tokens (the value of the provide property in a provider listed in the providers array). This is matched by the standard pattern used with constructor based injection, where the token is also a class name. (Refer back to DI Fundamentals for a refresher on tokens if this concept isn’t entirely clear). Sometimes, we may want the flexibility to use strings or symbols as the DI token. For example:

  1. import { connection } from './connection';
  2. @Module({
  3. providers: [
  4. {
  5. provide: 'CONNECTION',
  6. useValue: connection,
  7. },
  8. ],
  9. })
  10. export class AppModule {}

In this example, we are associating a string-valued token ('CONNECTION') with a pre-existing connection object we’ve imported from an external file.

Notice In addition to using strings as token values, you can also use JavaScript symbols.

We’ve previously seen how to inject a provider using the standard constructor based injection pattern. This pattern requires that the dependency be declared with a class name. The 'CONNECTION' custom provider uses a string-valued token. Let’s see how to inject such a provider. To do so, we use the @Inject() decorator. This decorator takes a single argument - the token.

  1. @Injectable()
  2. export class CatsRepository {
  3. constructor(@Inject('CONNECTION') connection: Connection) {}
  4. }
  1. @Injectable()
  2. @Dependencies('CONNECTION')
  3. export class CatsRepository {
  4. constructor(connection) {}
  5. }

Hint The @Inject() decorator is imported from @nestjs/common package.

While we directly use the string 'CONNECTION' in the above examples for illustration purposes, for clean code organization, it’s best practice to define tokens in a separate file, such as constants.ts. Treat them much as you would symbols or enums that are defined in their own file and imported where needed.

Class providers: useClass

The useClass syntax allows you to dynamically determine a class that a token should resolve to. For example, suppose we have an abstract (or default) ConfigService class. Depending on the current environment, we want Nest to provide a different implementation of the configuration service. The following code implements such a strategy.

  1. const configServiceProvider = {
  2. provide: ConfigService,
  3. useClass:
  4. process.env.NODE_ENV === 'development'
  5. ? DevelopmentConfigService
  6. : ProductionConfigService,
  7. };
  8. @Module({
  9. providers: [configServiceProvider],
  10. })
  11. export class AppModule {}

Let’s look at a couple of details in this code sample. You’ll notice that we define configServiceProvider with a literal object first, then pass it in the module decorator’s providers property. This is just a bit of code organization, but is functionally equivalent to the examples we’ve used thus far in this chapter.

Also, we have used the ConfigService class name as our token. For any class that depends on ConfigService, Nest will inject an instance of the provided class (DevelopmentConfigService or ProductionConfigService) overriding any default implementation that may have been declared elsewhere (e.g., a ConfigService declared with an @Injectable() decorator).

Factory providers: useFactory

The useFactory syntax allows for creating providers dynamically. The actual provider will be supplied by the value returned from a factory function. The factory function can be as simple or complex as needed. A simple factory may not depend on any other providers. A more complex factory can itself inject other providers it needs to compute its result. For the latter case, the factory provider syntax has a pair of related mechanisms:

  1. The factory function can accept (optional) arguments.
  2. The (optional) inject property accepts an array of providers that Nest will resolve and pass as arguments to the factory function during the instantiation process. The two lists should be correlated: Nest will pass instances from the inject list as arguments to the factory function in the same order.

The example below demonstrates this.

  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider: OptionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. })
  12. export class AppModule {}
  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. })
  12. export class AppModule {}

Alias providers: useExisting

The useExisting syntax allows you to create aliases for existing providers. This creates two ways to access the same provider. In the example below, the (string-based) token 'AliasedLoggerService' is an alias for the (class-based) token LoggerService. Assume we have two different dependencies, one for 'AliasedLoggerService' and one for LoggerService. If both dependencies are specified with SINGLETON scope, they’ll both resolve to the same instance.

  1. @Injectable()
  2. class LoggerService {
  3. /* implementation details */
  4. }
  5. const loggerAliasProvider = {
  6. provide: 'AliasedLoggerService',
  7. useExisting: LoggerService,
  8. };
  9. @Module({
  10. providers: [LoggerService, loggerAliasProvider],
  11. })
  12. export class AppModule {}

Non-service based providers

While providers often supply services, they are not limited to that usage. A provider can supply any value. For example, a provider may supply an array of configuration objects based on the current environment, as shown below:

  1. const configFactory = {
  2. provide: 'CONFIG',
  3. useFactory: () => {
  4. return process.env.NODE_ENV === 'development' ? devConfig : prodConfig;
  5. },
  6. };
  7. @Module({
  8. providers: [configFactory],
  9. })
  10. export class AppModule {}

Export custom provider

Like any provider, a custom provider is scoped to its declaring module. To make it visible to other modules, it must be exported. To export a custom provider, we can either use its token or the full provider object.

The following example shows exporting using the token:

  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider: OptionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. exports: ['CONNECTION'],
  12. })
  13. export class AppModule {}
  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. exports: ['CONNECTION'],
  12. })
  13. export class AppModule {}

Alternatively, export with the full provider object:

  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider: OptionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. exports: [connectionFactory],
  12. })
  13. export class AppModule {}
  1. const connectionFactory = {
  2. provide: 'CONNECTION',
  3. useFactory: (optionsProvider) => {
  4. const options = optionsProvider.get();
  5. return new DatabaseConnection(options);
  6. },
  7. inject: [OptionsProvider],
  8. };
  9. @Module({
  10. providers: [connectionFactory],
  11. exports: [connectionFactory],
  12. })
  13. export class AppModule {}