02 Dec 2020
4 min

How to Follow the Dependency Inversion Principle in NestJS and Angular

In the NestJS documentation, we can find the following sentence:

Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications.

Let’s test this statement by checking if Nest allows us to easily follow one of the SOLID principles: the Dependency Inversion Principle.

Nest is highly inspired by Angular, so all recipes in this article work in Angular as well.

For a quick reminder, the principle states:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces).
  2. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

Example

To explain how to implement DIP, let’s first consider the following example.
We create an application that will analyze data about our repositories on the GitHub platform. Our current task is to implement an endpoint that will return the number of active pull requests for a given repository.

That functionality can be quickly implemented as shown below, but it does not comply with our principle:

import { Controller, Get, HttpModule, HttpService } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PullRequest } from 'app/domain';

@Controller()
export class AppController {
  constructor(private http: HttpService) {}

  @Get('repository/:id/pending-prs')
  getNumberOfPendingPrs(id: string): Observable<number> {
    return this.http
      .get<PullRequest[]>(`https://api.github.com/repos/${id}/pulls`)
      .pipe(map(res => res.data.length));
  }
}

Even moving that HTTP call to a dedicated service is not a proper way to hide the implementation from the controller:

import { Controller, Get, HttpService } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { GithubService } from 'app/infrastructure';

@Controller()
export class AppController {
  constructor(private githubService: GithubService) {}

  @Get('repository/:id/pending-prs')
  getNumberOfPendingPrs(id: string): Observable<number> {
    return this.githubService.getPullRequests(id).pipe(map(prs => prs.length));
  }
}
import { HttpService, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PullRequest } from 'app/domain';

@Injectable()
export class GithubService {
  constructor(private http: HttpService) {}
  getPullRequests(id: string): Observable<PullRequest[]> {
    return this.http
      .get<PullRequest[]>(`https://api.github.com/repos/${id}/pulls`)
      .pipe(map(res => res.data));
  }
}

Implementation of the Dependency Inversion Principle

The proper implementation should look like this:

import { Controller, Get } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { RepositoryService } from 'app/interfaces';

@Controller()
export class AppController {
  constructor(private repositoryService: RepositoryService) {}

  @Get('repository/:id/pending-prs')
  getNumberOfPendingPrs(id: string): Observable<number> {
    return this.repositoryService
      .getPullRequests(id)
      .pipe(map(prs => prs.length));
  }
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { GithubInfrastructureModule } from 'app/infrastructure-github';

@Module({ imports: [GithubInfrastructureModule], controllers: [AppController] })
export class AppModule {}
import { HttpModule, Module } from '@nestjs/common';
import { RepositoryService } from 'app/interfaces';
import { GithubRepositoryService } from './github-repository.service';

@Module({
  imports: [HttpModule],
  providers: [
    { provide: RepositoryService, useClass: GithubRepositoryService }
  ],
  exports: [RepositoryService]
})
export class GithubInfrastructureModule {}
import { HttpService, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { PullRequest } from 'app/domain';
import { RepositoryService } from 'app/interfaces';

@Injectable()
export class GithubRepositoryService implements RepositoryService {
  constructor(private http: HttpService) {}
  getPullRequests(id: string): Observable<PullRequest[]> {
    return this.http
      .get<PullRequest[]>(`https://api.github.com/repos/${id}/pulls`)
      .pipe(map(res => res.data));
  }
}
import { Observable } from 'rxjs';
import { PullRequest } from 'app/domain';

export abstract class RepositoryService {
  abstract getPullRequests(id: string): Observable<PullRequest[]>;
}
  1. We need to create an abstraction layer for getting the collection of pull requests. This abstraction is achieved by the RepositoryService abstract class.
  2. To the AppController, we are trying to inject something that is hidden by the RepositoryService injection token.
  3. The GithubInfrastructureModule says that in that place, it should be provided a GithubRepositoryService class.

OK, but why couldn’t we use an ordinary interface as an abstraction layer?

The answer is what happens with interfaces during the transpiling process from TypeScript to JavaScript. The problem is that we will lose all information about the RepositoryService interface’s existence and what should be injected to the AppController, and basically, it is not possible to pass an interface as a property value inside module providers.

The situation is completely different when it comes to classes. Even an abstract class after transpilation will be an ordinary class that can be used as an injection token. In TypeScript, we can implement a class by another class that is the same as an interface.

Why Is This So Important?

Let’s say that the requirements of our application have changed. We need to also support the repositories stored on Bitbucket as a dedicated application instance. If we hadn’t added it earlier, now we would have to add a lot of ifs in our services and controllers to prepare a proper HTTP call for the needed data.

With that elegantly hidden data source layer, we can just create a dedicated module for Bitbucket’s services and properly import our feature model as follows:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { GithubInfrastructureModule } from 'app/infrastructure-github';
import { BitbucketInfrastructureModule } from 'app/infrastructure-bitbucket';

@Module({
  imports: [
    ...(process.env.provider === 'GITHUB' ? [GithubInfrastructureModule] : []),
    ...(process.env.provider === 'BITBUCKET' ? [BitbucketInfrastructureModule] : [])
  ],
  controllers: [AppController]
})
export class AppModule {}

Now the GithubRepositoryService or the BitbucketRepositoryService will be injected into the AppController depending on the environment without any changes in the code of the outer layers.

Good examples of where this applies in an Angular application are when:

  • We are creating web and mobile applications and they are loading data in a different way.
  • We are building an application with SSR. While receiving data on the server side, we also want to save them in the TransferState. And on the browser side, we want to get them from it.

In both cases, following the Dependency Inversion Principle will help us implement and reduce changes and logic in high-level modules that use our data access layer. The only difference is that we basically shouldn’t depend on the environment to decide which module should be imported.

Summary

Following the SOLID Principles gives us a lot of benefits. Moreover, they make our system reusable, maintainable, scalable, testable, and more. Nest and Angular allow us to use them in an easy and elegant way.

If you are interested in how we can use GithubRepositoryService and BitbukcetRepositoryService in the same application instance, please check this repo.

After all, the statement from Nest’s documentation can be considered as a truth!

Frequently asked questions

How do I follow the Dependency Inversion Principle in NestJS?

Define an abstraction as an abstract class, such as RepositoryService with an abstract method getPullRequests(id: string), and inject that class into your controller instead of a concrete service. Then bind the implementation in a module with { provide: RepositoryService, useClass: GithubRepositoryService } and export the token. The controller never imports the HTTP details, so the data source can change without touching it.

Why use an abstract class instead of an interface for dependency injection in NestJS?

Interfaces are erased during the TypeScript-to-JavaScript transpilation, so they cannot be passed as a provider token in module providers. An abstract class compiles to an ordinary JavaScript class that still exists at runtime and can serve as an injection token. A concrete class like GithubRepositoryService can then implement it with implements RepositoryService, giving you the same contract an interface would.

Does the Dependency Inversion Principle work the same way in Angular?

Yes, the article notes that Nest is highly inspired by Angular, so the same recipe works in Angular: an abstract class used as an injection token, bound to a concrete implementation in providers. This helps when web and mobile builds load data differently, or in SSR apps where server-fetched data is saved in TransferState and read in the browser. High-level components then depend only on the abstraction.

Why is injecting a concrete service into a controller still a Dependency Inversion violation?

Injecting a concrete GithubService still makes the controller depend on a low-level module, even though the HTTP call has moved out of it. The controller remains coupled to GitHub's implementation, so adding Bitbucket would require conditionals in the service or controller layer. Depending on an abstraction like RepositoryService instead keeps the high-level controller unchanged.

How do I switch between GitHub and Bitbucket data sources in NestJS without changing the controller?

Create a separate infrastructure module for each provider that supplies the same abstract token, then import the right one conditionally in AppModule. In the article's example, GithubInfrastructureModule or BitbucketInfrastructureModule is chosen based on process.env.provider. The AppController remains unchanged, because Nest injects whichever RepositoryService implementation the active module provides.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.