This is me…

Introduction to Building Microservices with NodeJs using NestJs Framework

Published 3 year ago20 min read0 comments

Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript), and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!

Nest provides a level of abstraction above these common Node.js frameworks (Express/Fastify), but also exposes their APIs directly to the developer. This gives developers the freedom to use the myriad of third-party modules which are available for the underlying platform.

In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications. This has given rise to awesome projects like Angular, React and Vue, which improve developer productivity and enable the creation of fast, testable, and extensible frontend applications. However, while plenty of superb libraries, helpers, and tools exist for Node (and server-side JavaScript), none of them effectively solve the main problem of - Architecture.

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. The architecture is heavily inspired by Angular.

Installation

Steps

To get started, you can either scaffold the project with the Nest CLI, or clone a starter project from github (both will produce the same outcome).

					    
npm i -g @nestjs/cli

nest new project-name
					
				
Here, I have given as nest new intro project directory. And select npm
After selecting the npm, all the modules will be installed.
Folder structure and dependencies by nestjs

Core Concepts of Nest.js

If you are not yet familiar with Nest.js, there are three basic concepts that you will be working on all the time; 'Modules', 'Controllers', and 'Services'.

Modules

Modules encapsulate logic into reusable pieces of code (components). A module is a class annotated with a @Module() decorator. The @Module() decorator provides metadata that Nest makes use of to organize the application structure.

app.module.ts
					
//app.module.ts
@Module({
  imports: [],       // Other modules
  controllers: [],   // REST controllers
  providers: [],     // Services, Pipes, Guards, etc
});

export class AppModule {}
					
				

The @Module() decorator takes a single object whose properties describe the module:

providers the providers that will be instantiated by the Nest injector and that may be shared at least across this module
controllers the set of controllers defined in this module which have to be instantiated
imports the list of imported modules that export the providers which are required in this module
exports the subset of providers that are provided by this module and should be available in other modules which import this module. You can use either the provider itself or just its token (provide value)
Controllers
app.controller.ts

Used to handle REST operations (HTTP methods).

app.controller.ts
					
//app.controller.ts
@Controller() //Decorator indicating that the following TypeScript class is a REST controller
export class AppController {
    constructor(
        private readonly appService: AppService //Service available through Dependency Injection  
    ) {} 
    
    @Get() //HTTP method handler
    getHello(): string {
        return this.appService.getHello(); //Calling a service method
    }
}
					
					
@Request(), @Req() req
@Response(), @Res()* res
@Next() next
@Session() req.session
@Param(key?: string) req.params / req.params[key]
@Body(key?: string) req.body / req.body[key]
@Query(key?: string) req.query / req.query[key]
@Headers(name?: string) req.headers / req.headers[name]
@Ip() req.ip
@HostParam() req.hosts
Services

Services are used to handle logic and functionality. Service methods are called from within a controller. The service will be responsible for data storage and retrieval, and is designed to be used by the controller, so it's a good candidate to be defined as a provider.

app.service.ts
						
//app.service.ts
@Injectable() //Decorator that marks a TypeScript class a provider (service)
export class AppService {

    /** 
     * Other services, repositories, 
     * CQRS handlers can be accessed through Dependency Injection
    **/
    constructor() {} 
                            
    getHello(): string {
        return 'Hello World!'; //Plain functionality
    }
}
						
					
Run the NestJs

To run this project you have to check the package.json file where all the script commands are mentioned.

package.json
						
npm run start:dev
						
					
Successfully running the code wihtout any errors
Check on your browser PORT: 3000
Running on browser


Next

JavaScript Best Practices for Readable and Maintainable Code