Introduction to Nestjs

NestJS is a framework for developing Node.js applications on the server side. It is written in TypeScript and provides an in-application architecture that enables more maintainable application development. Its architecture is quite inspired by Angular, which facilitates the work of the development team by not having to use two different ways of working in the backend and in the frontend.
When developing a project, it is important to have a well-planned structure and strategy for organizing the code. One of the reasons why the NestJS framework arises is precisely to make it easier for developers to have a modular code structure, which facilitates the development of enterprise NodeJS applications. NestJS is a NodeJS framework built on top of NodeJS and TypeScript, and makes use of Express. It also offers support for the main databases (MySQL, PostgreSQL, Oracle, SQLite, MongoDB, …​) and an architecture inspired by Angular, characteristics that make it a very interesting framework.
Now that we know what NestJS is, let’s learn how to install it.



NestJs Installation


To use Nestjs, we need to install the Nestjs CLI tool, which is available from the NPM repositories. For the installation it is necessary to have Nodejs already installed on our computer.

$ npm i -g @nestjs/cli
$ nest new project-name
$ cd project-name
$npm runstart:dev

After installing the following commands, in our localhost:3000 we will get the following.

 

 

Nestjs key concepts


Here are some key concepts to understand to develop an application in Nestjs. Any basic application to build involves interacting with these pieces of software, it is necessary to know them for the best use of the framework.

Controllers: Piece of software in charge of receiving and processing HTTP requests. Controllers are identified with the @Controller() decorator.
Providers: The main idea of the providers is to inject functionalities to every part that needs it. Providers are identified with the @Injectable() decorator.
Modules: Piece of software in charge of grouping components, functionalities, encapsulating and resolving dependencies. Modules are identified with the @Module() decorator.
Pipes: Piece of software in charge of performing data transformations and validations following the pipe filter pattern.
Guards: Piece of software in charge of determining if a request is accepted depending on certain conditions (such as permissions, roles, ACLs, etc.).
Dependency Injection: An object-oriented design pattern that resolves all dependencies that an object needs to be instantiated.

 

Operation of Services and Drivers


Services take care of abstracting the complexity and business logic to a separate class. The NestJS CLI adds the @Injectable decorator to services during their creation. These services may be injected into controllers or into other services.

app.service.ts file:

import { Injectable } from ‘@nestjs/common’;

@Injectable() 1
export class AppService {
getHello(): string { 2
return ‘Hello World!’;
}
}

1) Decorator that allows the service to be injected into controllers and other services
2)Function that provides a certain functionality

On the one hand, the controller is in charge of listening to the requests that arrive at the application. On the other hand, it is responsible for preparing the responses provided by the application. The NestJS CLI adds the @Controller decorator to controllers during their creation. NestJS allows the use of routes as parameters of the @Controller decorator

app.controller.ts file

import { Controller, Get } from ‘@nestjs/common’;
import { AppService } from ‘./app.service’; 1

@Controller() 2
export class AppController {
constructor(private readonly appService: AppService) {} 3

@Get() 4
getHello(): string { 5
return this.appService.getHello(); 6
}
}

1)Import of the service
2) Decorator that tells NestJS that it is a controller
3)Service injection
4) HTTP request type and route (empty) served by the controller
5) Function to be executed after invoking the route with a GET request
6) Invocation of the service that resolves the request

 

Creating our first service and controller

From the command line we will use the NestJS CLI.

$ nest g service tutorial
$ nest g controller tutorial

The created service is available in tutorial/tutorial.service.ts and the created controller is available in tutorial.controller.ts. The creation of the service and controller have modified the app.module.ts file by adding them to the list of services and controllers for the application.

The app.module.ts file

import { Module } from ‘@nestjs/common’;
import { AppController } from ‘./app.controller’;
import { AppService } from ‘./app.service’;
import {

TutorialService } from ‘./tutorial/tutorial.service’;
import { TutorialController } from ‘./tutorial/tutorial.controller’;

@Module({
imports: [],
controllers: [AppController, TutorialController], 1
providers: [AppService, TutorialService], 2
})
export class AppModule {}

1) Driver List
2) List of providers


The service

file tutorial/tutorial.service.ts

import { Injectable } from ‘@nestjs/common’;

@Injectable()
export class TutorialService {
findAll(): any { 1
return ‘​​Hello World!’;
}
}

1) Example of a function that merely indicates that it is working when it is called.

 

The controller

We start by simply adding for now:

1) The constructor where the service is injected to be able to use it
2)Creating the first route and the associated HTTP method that we are going to test 1

import { Controller, Get } from ‘@nestjs/common’;
import { TutorialService } from ‘./tutorial.service’;

@Controller(‘tutorial’)
export class TutorialController {
constructor(private tutorialService: TutorialService) {} 2

@Get() 3
findAll() { 4
return this.tutorialService.findAll(); 5
}
}

1) Import of the service that provides the data
2) Constructor with the injected service
3) Decorator to indicate the route served and the HTTP method
4) Method associated with the request
5) Call to the method of the service that resolves the request

 

Structure of a project


Now that we know a little more about NestJs, we will see the structure of the created project, which includes files tutorial.service.spect and tutorial.controller.spect.ts that refer to the tests, which we will not talk about in this section. this short tutorial

 


As we can see, the first thing we find is a Dist folder, which corresponds to the same Nest application but transpiled. Then we find the node_module folder where our project dependencies are stored. The third folder named src is where all our source code is stored. Below is the test folder which is used when the app is finished. And finally we find useful files for our project such as eslint that is used for the style rules of our project with TypeScript, gitignore that are the folders that are ignored when working in our NestJS application, prettier that is used to format our code, nest-cli.json which is the main NestJS file where you can assign which is the main folder in our case src, we also have the package-log and package.json where the scripts and development dependencies are stored and finally the README file which is an instruction file for our project.

Now that we have a base on NestJS, we invite you to continue learning on its official site https://nestjs.com/.

Federico Arnau

Developer