Building Microservices with NestJS
Tags: nestjs, react, javascript, programming
Published: 2023-08-29 06:09:26

<h2><strong>The Architecture of Microservices:</strong></h2>
Microservices architecture is a way of developing software systems as independently deployable services. In this architecture, an application is built as a collection of small modular services communicating with each other.

Each microservice focuses on doing one thing well and can be developed, tested, deployed, and scaled independently.

Building microservices with NestJS is important for several reasons. Firstly, NestJS provides an optimized framework designed specifically for microservices architecture.

It handles challenges like dependency management, asynchronous communication, and scalability that are common in complex microservices ecosystems.

NestJS uses progressive JavaScript, TypeScript, and proven architectural patterns like dependency injection to create consistent, enterprise-grade services.

Secondly, NestJS increases developer productivity and velocity. The declarative, modular architecture and out-of-the-box developer tooling like the CLI allows developers to focus on business logic rather than building boilerplate.

Built-in capabilities like validation, serialization, and CORS handling also accelerate development.

<strong>Some key characteristics of microservices architecture:</strong>
<ul>
 	<li>Services are independently deployable - each service can be deployed independently without needing to deploy the entire application.</li>
 	<li>Services are organized around capabilities - services are broken down based on business capabilities.</li>
 	<li>Services can be implemented using different programming languages and technologies - since each service is independent, they can use whatever language or technology makes the most sense.</li>
 	<li>Services communicate via APIs - services expose APIs that other services can consume. Common protocols used are REST, gRPC, or asynchronous messaging.</li>
 	<li>Services are loosely coupled and highly cohesive but loosely coupled with others. This allows for easy maintenance and flexibility.</li>
 	<li>Services can be independently scaled - services can be scaled based on demand, allowing high scalability.</li>
</ul>
Microservices architecture enables easier agile development and deployment of complex applications. It also helps with scalability and maintaining services. The downside is the complexity of coordinating and deploying many independent services.
<h4><strong>NestJS Advantages for Microservices:</strong></h4>
NestJS is a progressive Node.js framework that provides an ideal toolkit for building efficient, scalable microservices in TypeScript. Here are some of the advantages of using NestJS:
<ul>
 	<li><strong>Built-in Support for Microservices</strong> - NestJS has first-class support for microservices architecture. It makes it easy to build independent, deployable services.</li>
 	<li><strong>Dependency Injection</strong> - NestJS provides dependency injection out of the box. This allows for loose coupling between services and better modularity.</li>
 	<li><strong>Easy to Scale</strong> - NestJS uses Node.js and JavaScript, so it's easy to scale microservices across multiple nodes. The architecture also aids in scalability.</li>
 	<li><strong>TypeScript</strong> - NestJS uses TypeScript, which provides type safety and other benefits for large enterprise applications.</li>
 	<li><strong>Modular with MVC</strong> - Code is modularized into modules, controllers, services, and providers. This makes code easier to maintain and organize at scale.</li>
 	<li><strong>Built-in CLI</strong> - NestJS CLI allows quick boilerplate code generation, allowing developers to focus on business logic.</li>
 	<li><strong>First-class Support for Open APIs and Protocols</strong> - NestJS works well with common microservice API protocols like gRPC, MQTT, Redis, and more.</li>
 	<li><strong>Rich Ecosystem of Modules</strong> - A rich module ecosystem for tasks like configuration, logging, caching, rate limiting, etc., helps accelerate development.</li>
</ul>
NestJS combines the best features of Node, TypeScript, and architectural patterns like dependency injection to build scalable and maintainable microservices.
<h4><strong>Setup of the Project:</strong></h4>
Here are the steps to set up a new microservice project with NestJS:

<strong>Step 1: Install Nest CLI using npm:</strong>

`npm i -g @nestjs/cli`

This installs the NestJS CLI globally on your system.

<strong>Step 2: New Microservice should be Created</strong>

Use the Nest CLI to generate a new microservice application:

`nest new microservice-name`

This will scaffold a new microservice app, folders, files, and sample code.

<strong>Step 3: Navigate to the directory of the newly created microservice application</strong>

`cd microservice-name`

Change to the app directory that was just created.

<strong>Step 4: Creating a Module</strong>

Modules are used to organize code into logical boundaries in NestJS. Under src/ create a new module:

`nest g module cats`

This will generate a CatsModule module under src/cats/cats.module.ts

<strong>Step 5: Creating a Controller:</strong>

Controllers handle incoming requests and return responses in NestJS. Generate a new controller:

`nest g controller cats`

This will create a CatsController under src/cats/cats.controller.ts that is already imported into the CatsModule

<strong>Step 6: Creating a Service</strong>

Services contain business logic and handle data access and processing. Generate a cats service:

`nest g service cats`

This creates a CatsService service class under src/cats/cats.service.ts that is imported into the CatsModule.

<strong>Step 7: Configure Communication</strong>

The generated files include sample code showing how the controller uses the service. The controller's request handling methods can call methods on the service class to execute business logic.

<strong>Step 8: Main File Configuration</strong>

Open src/main.ts and update any required configuration for your microservice app. The NestFactory is used to create the Nest app instance.

<strong>Step 9: Start your microservice by running</strong>

`npm run start`

This will compile the TypeScript code and start the application. The microservice will be running on the configured port.
<h4><strong>Module Organization</strong></h4>
NestJS promotes modularity by organizing code into modules, controllers, services and providers. Here is an example workflow to create a modular microservice:

<strong>Example: How to organize a microservice in NestJS with its module, controller, and service.</strong>

<strong>Step 1: Create a new microservice called "user-service</strong>

`nest new user-service`

<strong>Step 2: Navigate to Microservice Directory</strong>

`cd user-service<`

<strong>Step 3: Create a new module for the microservice</strong>

`nest g module users`

This will generate a UsersModule

<strong>Step 4: Create a controller that handles incoming HTTP requests</strong>

`nest g controller users`

This creates a UsersController

<strong>Step 5: Create a service that contains the business logic</strong>

`nest g service users`

This generates a UsersService

<strong>Step 6: Define routes for the controller</strong>

In UsersController define routes and handler methods for requests:
```javascript
@Get()
findOne() {
  return this.usersService.findOne(); 
}
```
<strong>Step 7: Service Logic</strong>

Implement business logic for the service method called by the controller:
```javascript
findOne() {
  return 'user';
}
```
<strong>Step 8: Update Module Definition- import the controller and service</strong>

In UsersModule import the controller and service:

`imports: [UsersController, UsersService]`

<strong>Step 9: Bootstrap the Microservice: Update the src/main.ts</strong>

Add required app setup code:
```javascript
const app = await NestFactory.create(UsersModule);
await app.listen(3000);
```
<strong>Step 10: Run the microservice</strong>

`npm run start`

This modular organization makes it easy to maintain clean, independent services. The controller handles web requests, while the service handles business logic using providers. The module ties them together.

In summary, NestJS provides an ideal framework for building scalable microservices using Node.js and TypeScript.

With its efficient modularity via modules, services, and developer tooling, NestJS accelerates microservice development and deployment.

If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h1><a href="https://dev.to/comfortdeola/what-is-asynchronous-javascript-317g#resources" name="resources"></a>Resources</h1>
Here are some blogs/posts I read as a reference. You should check them out:
<ul>
 	<li><a href="https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j">Asynchronous JavaScript (JS) Demystified</a> By <a href="https://dev.to/thanhtr99270163/asynchronous-javascript-js-demystified-3b8j">Thanh Truong’s</a></li>
 	<li><a href="https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/">JavaScript Async/Await Tutorial – Learn Callbacks, Promises, and Async/Await in JS by Making Ice Cream 🍧🍨🍦</a> By <a href="https://www.freecodecamp.org/news/javascript-async-await-tutorial-learn-callbacks-promises-async-await-by-making-icecream/">Joy Shaheb</a></li>
 	<li><a class="attrlink" href="https://www.codecademy.com/learn/learn-how-to-code?periods=year&amp;plan_id=proGoldAnnualV2&amp;utm_source=pepperjam&amp;utm_medium=affiliate&amp;utm_term=96525&amp;clickId=4438617034&amp;pj_creativeid=8-12462&amp;pj_publisherid=96525" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Programming</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/08/4-javascript-email-frameworks-nodemailer-sendgrid-smtp-js-and-mailgun/" target="_blank" rel="noopener noreferrer nofollow">Javascript Email with Nodemailer</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/01/18/how-to-send-an-email-in-node-js-using-nodemailer/" target="_blank" rel="noopener noreferrer nofollow">How to send an email in node.js using nodemailer</a></li>
 	<li><a class="attrlink" href="https://www.w3schools.com/js/js_arrays.asp" target="_blank" rel="noopener noreferrer nofollow">Javascript Array method</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/09/20-best-javascript-frameworks-for-2023/" target="_blank" rel="noopener noreferrer nofollow">20 Best React JavaScript Frameworks For 2023</a></li>
</ul>