Microservices with NestJS

Share:

NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. It offers a strong modular architecture that takes advantage of TypeScript's strong type checking and object-oriented programming capabilities. In this tutorial, we will delve into the details of how you can implement microservices in NestJS. We will be using the characters and features of a hypothetical movie as references for our code examples and discussion scenarios.

Microservices architecture offers a way to break down a single large application into smaller, loosely coupled applications. Each one of these small applications (microservices) can be developed and deployed independently. Using the microservices architecture, NestJS enables you to build scalable, maintainable, and testable applications.

Imagine creating a movie application where every feature of the application is treated as a separate, deployable unit. For instance, you could have one microservice to handle movie ratings, another for user reviews and another for user authentication.

Setup

Ensure you have NodeJS and NestJS installed on your machine. You can install NestJS via npm by running the following command:

npm i -g @nestjs/cli

Initializing a new NestJS project is pretty straightforward. Run the following command to generate a new application:

nest new movie-microservices

Creating Microservices

Microservices in NestJS are developed with the same programming model as typical NestJS applications. However, they differ in terms of how they communicate with the client or other microservices. They typically do this using the Transport layer.

There are multiple transport strategies available in NestJS - TCP, Redis, NATS, gRPC, RabbitMQ, Kafka and MQTT. We will focus on the TCP strategy in this tutorial.

To create your first microservice, first create a new folder called 'ratings'. Inside this folder, create a file 'ratings.controller.ts'. This file will manage all requests for the 'ratings' microservice.

mkdir ratings
touch ratings/ratings.controller.ts

Here's how the 'ratings.controller.ts' might look:

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class RatingsController {
  
  @MessagePattern('getRatings')
  getRatings() {
    return [
      { movie: 'Inception', rating: 8.7 },
      { movie: 'Interstellar', rating: 8.6 }
    ];
  }
}

In the above code, the MessagePattern decorator is used to define a message route that this microservice will listen for. Let's now create a similar microservice for 'reviews'.

NestJS Microservice Client

When working in a microservices environment, the need will arise to consume one microservice from another. Nest provides the ClientProxy class for making this easy. Let's consume the 'ratings' microservice from the 'reviews' microservice. First, we need to create a microservice client. Here is how you setup your client:

import { Client, ClientTCP } from '@nestjs/microservices';

export class ReviewsController {
  @Client({ port: 8877 }) // port where the microservice is running
  client: ClientTCP;

  /* rest of the class */
}

You can then call the send() method on this client to consume the 'ratings' microservice.

this.client.send('getRatings', {});

Running the Microservices

To run your NestJS microservice, you need to bootstrap it in your main.ts file. Here is how you do it:

import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { RatingsModule } from './ratings/ratings.module';

async function bootstrap() {
  const app = await NestFactory.create(RatingsModule);
  app.connectMicroservice({
    transport: Transport.TCP,
    options: {
      host: 'localhost',
      port: 8877,
    },
  });

  await app.startAllMicroservicesAsync();
  await app.listen(3000);
}
bootstrap();

Here, after connecting the application with the microservice using connectMicroservice(), we start all microservices using startAllMicroservicesAsync(). The server starts listening at the specified port.

Microservices in NestJS are powerful tools for developing distributed systems. They offer benefits like improved scalability and independent development and deployment of features which were part of a single monolith application. Moreover, they enable separation of concerns where each microservice is responsible for a specific feature. For our movie application, this practical architectural design translates into an efficient and well-structured system that makes development, management and scaling a breeze.

0 Comment


Sign up or Log in to leave a comment


Recent job openings