NestJS framework for building scalable applications

Nest (NestJS) is progressive Node.js framework for building scalable and efficient server-side applications by @KamilMysliwiec. Nest uses modern JavaScript, is built with Typescript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming),FRP (Functional Reactive Programming).

Nest makes use of HTTP server framework like Express (default) and optionally can be configured to use Fastify as well! Nest can provide a decent layer of abstraction above these frameworks,it also exposes these framework API to the developers, So that the developer can use myriad third-party modules that are available to each platform.

Nest provides an out-of-the-box application architecture which allows developers to create highly testable,scalable, loosely coupled and easily maintainable applications.Architecture is heavily inspired by angular.

Here’s a link to Nest open source repository on GitHub

Prerequisites

Please make sure that Node.js(>=10.13.0) is installed on your OS.

Installation

# To scaffold the project with Nest CLI, run the following commands

$ npm i @nestjs/cli
$ nest new project-name
$ npm run start

# Alternatively, to install Typescript starter Project with Git:

$ git clone https://github.com/nestjs/typescript-starter.git project
$ cd project
$ npm install
$ npm run start

Open your browser and navigate to http://localhost:3000/ .To install the JavaScript of the starter project use javascript-starter.git in command.

Building Blocks of NestJs

Given below are building blocks of Nest application.there are more of them but these are most important ones.

Controllers

“Controllers are responsible for handling incoming requests and returning responses to the client.” A controller is simply annotated with an @Controller()

  • Each controller has different routes to perform different operations.

Providers

Many of the basic Nest class may be treated as provider-services,repositories,factories,helpers and so on.The main idea of a provider is that it can inject dependencies;
A provider is simply a class annotated with an @Injectable()

  • Abstract all forms of complexity and logic to a separate class.

Example

message.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class MessageService {
getMessage() {
return 'Welcome User';
}
}
message.controller.ts

import { Controller, Get, Dependencies } from '@nestjs/common'; 
import { MessageService } from './message.service';

@Controller('message')
@Dependencies(CatsService)
export class MessageController {
constructor(service) {
this.service = MessageService;
}
@Get()
async findAll() {
return this.service.getMessage();
}

Modules

A module is a class with @Module decorator sends metadata to Nest required to determine which components,controllers or other resources will be used in application code and group them together into a single set.

message.module.ts

import { Module } from '@nestjs/common';
import { MessageController } from './message.controller';
import { MessageService } from './message.service';

@Module({
controllers: [MessageController],
providers: [MessageService],
})
export class MessageModule {}

Middleware

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application’s request-response cycle.Nest middleware fully supports Dependency Injection. Just as with providers and controllers, they are able to inject dependencies that are available within the same module. As usual, this is done through the constructor.

Applying middleware

There is no place for middleware in the @Module() decorator. Instead, we set them up using the configure() method of the module class. Modules that include middleware have to implement the NestModule interface. Let’s set up the LoggerMiddleware at the AppModule level.

app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { MessageModule } from './message/message.module';

@Module({
imports: [MessageModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes({ path: 'message', method: RequestMethod.GET });
}

Why Nest.js?

There are many reasons that make Nest suitable over other NodeJs Framework,some of them are –

  • Supports monorepo
  • Easy database interaction
  • Framework adaptive nature
  • Use third-party modules
  • Dependency injection container
  • Built in support for microservices & transport layers
  • Built in inversion of control
  • Nest is a splendid tool for Angular developers because of its familiarity.
  • Nest provides a structural development approach, which helps large teams build complex backends more consistently. This is important when using Express or any minimalist frameworks.
  • Integration with the most known libraries of GraphQL,REST, GraphQL, Websockets, gRPC… most of them still in an early stage of development, but Nest makes clear its intention about being a cutting edge framework that will help us to adapt the latest programming trends in our developments.
  • The moment you start building your application from scratch, a suite of tests is automatically generated and you can either execute them or extend them as you need.Thank to Jest, one the most used framework to run unit tests over JavaScript.But main advantage in Nest about unit testing is ability to create your components using dependency injection.This will allow you for example mock your data repository when running your tests so you can test in quick and easy way your application using any data range you want without needing to reproduce those data manually in your system.
  • TypeScript is integrated by default and is another great advantage of this framework.It also squeez the most out of it, being a crucial part of its design.some of them is highlight is :

# Decorators : Same way Angular does to define and extends the functionality of the system component .But it goes beyond it using them as a basis to define the structure of your application, allowing you to adapt reusable functionality in clean and readable way

# Types / Interfaces and DTO : Allow to define communication contracts between modules and layers in our system. Once we have our logic layer separated from the external layers, Nest provides us with the needed tools to make that logic robust enough.

DTOs can be defined for the most important entities in our application,withwe using classes or interfaces for it so we work with them easily in all our application modules.

But there is more.Our DTOs can be bound to the validation system included by default in nest using decorators to define the attributes of our entity.These validations will be applied though validation pipes that can be integrated in our endpoints.

Example

enum ROLES{
USER = ’user’
ADMIN = ‘admin’
}

Export class UserDto{
@IsNotEmpty
name : string;

@IsEmail
Email : string;

@IsNotEmpty()
@IsIn ( [ ROLES.USER, ROLES.ADMIN ])
role : string;

}
  • When developing a server, the two first dependencies that usually come first are API and Database. Nest abstract API layer using specific decorators (@Get, @Post, @Delete, @Patch, @Head, @Body…) so you can automatically attach your endpoint to functions completely abstracted from your API framework to which we can incorporate unit tests, etc.

Example

@Controller(‘user’)
export class UserController{

@Get()
async getUsers(@Query(ValidationPipe filter) {
// Get Users…
}
@Post()
async createUser(@Body() userData){ 
// Post UserData…
}
}
  • Nest comes with a built-in exceptions layer which is responsible for processing all unhandled exceptions across an application.When an exception is not handled by your application code, it is caught by this layer, which then automatically sends an appropriate user-friendly response.

Out of the box, this action is performed by a built-in global exception filter, which handles exceptions of type HttpException . When an exception is unrecognized (is neither HttpException nor a class that inherits from HttpException), the built-in exception filter generates the following default JSON response:

{
“statusCode”: 500
“Message”: “Internal server error”
}

Throwing standard exceptions

Nest provides a built-in HttpException class, exposed from the @nestjs/common package. For typical HTTP REST/GraphQL API based applications, it’s best practice to send standard HTTP response objects when certain error conditions occur.

The HttpException constructor takes two required arguments which determine the response:

  1. The response argument defines the JSON response body. It can be a string or an object as described below.
  2. The status argument defines the HTTP status code.

By default, the JSON response body contains two properties:

  1. statusCode: defaults to the HTTP status code provided in the status argument
  2. message: a short description of the HTTP error based on the status
 @Get()
async findAll() {
throw new HttpException({
status: HttpStatus.FORBIDDEN,
error: 'This is a custom message',
}, HttpStatus.FORBIDDEN);
}

Using the above, this is how the response would look:

{
"status": 403,
"error": "This is a custom message"
}

Exception Filter

While the base (built-in) exception filter can automatically handle many cases for you, you may want full control over the exceptions layer. For example, you may want to add logging or use a different JSON schema based on some dynamic factors. Exception filters are designed for exactly this purpose. They let you control the exact flow of control and the content of the response sent back to the client.

Let’s create an exception filter that is responsible for catching exceptions which are an instance of the HttpException class, and implementing custom response logic for them. To do this, we’ll need to access the underlying platform Request and Response objects. We’ll access the Request object so we can pull out the original url and include that in the logging information. We’ll use the Response object to take direct control of the response that is sent, using the response.json() method.

http-exception.filter.ts

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus();

response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}

The @Catch(HttpException) decorator binds the required metadata to the exception filter, telling Nest that this particular filter is looking for exceptions of type HttpException and nothing else. The @Catch() decorator may take a single parameter, or a comma-separated list. This lets you set up the filter for several types of exceptions at once.

  • Powerful CLI helps you to initialize, develop, and maintain your Nest applications. It assists in multiple ways, including scaffolding the project, serving it in development mode, and building and bundling the application for production distribution.

Command overview

Run nest <command> –help for any of the following commands to see command-specific options.

See usage for detailed descriptions for each command.

  1. new Scaffolds a new standard mode application with all boilerplate files needed to run.
  2. generate Generates and/or modifies files based on a schematic.
  3. build Compiles an application or workspace into an output folder.
  4. start Compiles and runs an application (or default project in a workspace).
  5. add Imports a library that has been packaged as a nest library, running its install schematic.
  6. update Update @nestjs dependencies in the package.json”dependencies” list to their @latest version.
  7. info Displays information about installed nest packages and other helpful system info.

So here we are, NestJS can be suited for and is intended to develop small or big server-side scalable applications.We have seen the features of Nest and If you found it insightful, you must give NestJS a fair chance and make go for it.To get more practical information check out the Link.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?