First Microservice in NestJs

·

3 min read

Hello and welcome to my blog! Today I'm going to talk about how to build a microservice in NestJs, a progressive Node.js framework that makes it easy and fun to create scalable and reliable server-side applications. If you're looking for a way to break down your monolithic app into smaller and more manageable pieces, or if you just want to learn new and exciting technology, then this post is for you!

What is a microservice?

A microservice is a software architecture pattern where a large, complex application is divided into many small, independent processes that communicate with each other through a network. Each microservice has its own responsibility and can be developed, tested, deployed, and scaled independently. This way, you can achieve better performance, scalability, maintainability, and flexibility for your application.

Why NestJs?

NestJs is an open-source library that provides everything you need to create microservices with Node.js. It is based on Express, the most popular web framework for Node.js, but it adds a lot of features and abstractions that make it easier to work with microservices. Some of the benefits of using NestJs are:

  • It supports several built-in transport layers for microservices, such as TCP, Redis, MQTT, NATS, gRPC, Kafka, and RabbitMQ. You can choose the one that suits your needs and switch between them without changing your application code.

  • It abstracts the implementation details of each transport layer behind a canonical interface for both request-response and event-based messaging. This means you can write your microservice logic without worrying about how to send or receive messages over the network.

  • It follows the principles of dependency injection, decorators, exception filters, pipes, guards, and interceptors. These are common concepts in modern web development that help you write clean, modular, and testable code.

  • It integrates well with other popular libraries and tools for Node.js, such as TypeScript, Jest, Swagger, GraphQL, Socket.io, etc. You can use them to enhance your microservice functionality and productivity.

How to create a microservice in NestJs?

Creating a microservice in NestJs is straightforward. You just need to follow these steps:

  1. Install the required package: npm i --save @nestjs/microservices

  2. Create a new NestJs project using the CLI: nest new my-microservice

  3. Edit the main.ts file to instantiate a microservice instead of an HTTP server:

import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
    const app = await NestFactory.createMicroservice(AppModule, {
        transport: Transport.TCP,
    });
    await app.listen();
}
bootstrap();
  1. Edit the app.module.ts file to define your microservice controllers and providers:

     import { Module } from '@nestjs/common';
     import { AppController } from './app.controller';
     import { AppService } from './app.service';
    
     @Module({
         controllers: [AppController],
         providers: [AppService],
     })
     export class AppModule {}
    
  2. Edit the app.controller.ts file to create your message handlers using decorators:

     import { Controller } from '@nestjs/common';
     import { MessagePattern } from '@nestjs/microservices';
     import { AppService } from './app.service';
    
     @Controller()
     export class AppController {
         constructor(private readonly appService: AppService) {}
    
         @MessagePattern('hello')
         getHello(): string {
             return this.appService.getHello();
         }
     }
    
  3. Edit the app.service.ts file to implement your business logic:

     import { Injectable } from '@nestjs/common';
    
     @Injectable()
     export class AppService {
         getHello(): string {
             return 'Hello World!';
         }
     }
    
  4. Run your microservice with npm run start

    That's it! You have created a simple microservice in NestJs that responds to messages with the pattern 'hello' with 'Hello World!'. You can test it using any TCP client or another NestJs microservice.

    Conclusion

    In this post, I have shown you how to create a microservice in NestJs using the request-response approach. I hope you enjoyed it and learned something new. NestJs is a great framework for building microservices with Node.js because it provides a lot of features and abstractions that make it easy and fun to work