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
Please make sure that Node.js(>=10.13.0) is installed on your OS.
# 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.
Given below are building blocks of Nest application.there are more of them but these are most important ones.
“Controllers are responsible for handling incoming requests and returning responses to the client.” A controller is simply annotated with an @Controller()
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()
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(); }
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 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.
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 }); }
There are many reasons that make Nest suitable over other NodeJs Framework,some of them are –
# 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; }
Example
@Controller(‘user’) export class UserController{ @Get() async getUsers(@Query(ValidationPipe filter) { // Get Users… } @Post() async createUser(@Body() userData){ // Post UserData… } }
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” }
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:
By default, the JSON response body contains two properties:
@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" }
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.
Run nest <command> –help for any of the following commands to see command-specific options.
See usage for detailed descriptions for each command.
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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork