Step Up Your Game and Start Using Nest

Written by sarrahpitaliya | Published 2021/09/16
Tech Story Tags: nestjs | nodejs | node.js-development | angular | graphql | typescript | coding | programming

TLDR The NestJs is a NodeJs framework, which is used to develop an efficient, scalable, and robust server-side applications. NestJS is coupled with the TypeScript framework that follows the Object-Oriented Programming and Functional Programming principles. NestJs has an architecture that lets you organize things in the same way as other NodeJs frameworks. It has become the most favorite in the. Angular developers' community to use NestJs for their back-end applications. It is also the most popular way to use GraphQL in your GraphQL-based applications.via the TL;DR App

Since I am fond of technology and a technical writer, I have always been to every corner of the world to attend various tech events and seminars. A few years back, I attended one tech event – JSCamp, which was a JavaScript-based tech event. I had come across different front-end frameworks, but there was one framework that stood out in the whole event and really grabbed my attention.
And this is why I am here. Well, I am talking about the NestJs – a progressive NodeJs framework. In this article, I am going to give you a small introduction to the basics of NestJs to every back-end developer who has some basic knowledge about the current front-end state of the art.

All About NestJS

NestJs is a NodeJs framework, which is used to develop an efficient, scalable, and robust server-side application. NestJS is coupled with the TypeScript framework that follows the Object-Oriented Programming and Functional Programming principles.
The fundamental benefit of the NestJS framework is its out-of-the-box application design, which enables developers to create highly scalable, loosely connected, tested, and easy-to-maintain applications.
As for REST development, NestJS offers you everything, such as:
It also comes up with a CLI, allowing you to create a skeleton following their architecture. Therefore, you can easily create a new controller with just one line of code:
nest g co name_of_your_controller
Now, you must be wondering – what if I get a chance to work with GraphQL?
Well, NestJS comes up with all built-in modules for all the requirements of your GraphQL. So, you can program using either a CodeFirst or a traditional ShcemaFirst technique.
Moreover, NestJS also provides a built-in module for testing purposes. This is quite easy to configure, that uses Jest and Supertest behind the scene.
“Nest takes NodeJs servers to a whole new level of scalability.”
Now, I am going to give you some of the best reasons that make Nest so great and why you should consider it for your next development project.

An Excellent Framework For Angular Developers

Nest turns out to be a great and preferred framework for every developer. However, it has become the most favorite in the Angular developers' community.
Angular development focuses on NestJs concepts. Therefore, it has become much easier to adopt the Nest technology and its concept for Angular developers.
However, I have had words with the Angular developer regarding the Nest framework.
“Nest framework coding is similar to Angular back-end coding.”
This is what an Angular developer said to me.
“Apart from the concepts, it also works amazing with Angular Universal.” Furthermore, a developer added.
Having a technical conversation with him and understanding the basic concepts, I could conclude that – as a developer, you can surely consider the NestJs framework for your back-end application. Moreover, if you have good expertise or knowledge of Angular, you must consider this as the learning curve becomes shallow.
“Nest is the new home for Angular developers!”

TypeScript-written Nest Apps

TypeScript, a typed superset of JavaScript, is used to write NestJs applications. This helps us during compile and execution time. It has various features, such as JavaScript's flexibility and the robustness of a typed language. And these functionalities are very useful for larger applications.
The optional typing system enables tooling, better IntelliSense, development experience, and refactoring. In addition, TypeScript also allows us to use the latest and updated features that have yet to be added to JavaScript.
The primary goal of NestJs is to create a scalable application. As a result, it’s clear that TypeScript will benefit Nest.

The Story of Architecture — Inspired by Angular 🏠

Working with a custom software development company, I know there are many developers who work on a single software project. Every developer has a different idea, mindset, code tactics, and mind. They work on the same codebase, though.
Therefore, every team member must have a common understanding of how to write and organize code. The proper format and guidelines of coding will help developers to maintain code consistency and style while working on the same project.
In fact, many server-side JavaScript frameworks don’t follow any architecture. But they have the flexibility that lets you organize things. Therefore, in my opinion, it consumes a lot of time to arrange elements and guidelines on how to develop a project.
That’s where NestJs comes into the picture and stands alone among other NodeJs frameworks. Here, NestJs has an opinionated project setup, whereas other frameworks don’t have many architectural concepts. As a result, NestJs was born to solve architecture.

NestJs: Unlike Another Back-end Framework

Once a full-stack developer said to me, “We’ve always been on the front foot to bring both front-end and back-end technologies together, but it has never been this close.”
Built on top of Express, TypeScript, and NodeJs development, it follows the JavaScript application approach – efficiency and scalability, without compromising complexity that back-end applications always cater to.
Well, this all happens because of TypeScript, as it allows back-end developers to identify some code similarities in the development section.
So, now let’s explore the architectural similarities.

Core Fundamentals

NestJs leverages decorators. This helps you define and analyze the various components we might have. A subset of the NestJS decorators follows the given approach:
@Controller
: It handles incoming requests and returns responses to the client. Generally, many endpoints are encountered using HTTP requests.
@Catch
: It’s also known as exception filters. It follows a simple method to handle concrete exceptions thrown by the controllers.
@Injectable
: It’s used to inject in other classes.
@Module
: It’s used to aggregate related components.
Dependency Injection, an IOC design principle, is critical for connecting various layers and structuring our application.
So, now I am going to go through some of the advanced concepts, methods, and components which you can use to implement.
Pipes: It's used for transforming and validating data.
Guards: Angular counterpart is one type of Guards. It lets you decide whether the navigation should be allowed to the specific route or not.
Middleware: Before a route-handler is executed, this function is used to run any code over the incoming requests.
Interceptors: It’s an AOP-oriented component used to bind extra logic before or after executing a controller method.

The First Step

So, using NestJS, let’s build the basic CRUD (Create, Read, Update, Delete) application.
Having said earlier, if you are a developer, who is familiar with TypeScript, NodeJS, and REST/GraphQL, then developing a project with NestJS is very easy and simple.
“The more knowledge you’ve, the easier things will be for you, irrespective of the technology you are working with.”
So, now you have to install NodeJS in your system and run the given command:
npm i -g @nestjs/cli
Now, nest cli will be installed on your system to develop an application with the help of their client.
Now, let’s create a new project with the following command.
nest new project-name
Here, we will create a project named nest-demo.
Now, a scaffold will be created for your project. So, you have two options to choose from yarn and npm. Here, I am going to choose yarn.
Let me give you an example here:
apple-MacBook-Pro:code apple$ nest new nest –demo
We will scaffold your app in a few seconds..
CREATE /nest-demo/.prettierrc (51 bytes)
CREATE /nest-demo/README.md (3370 bytes)
CREATE /nest-demo/nest-cli.json (84 bytes)
CREATE /nest-demo/package.json (1721 bytes)
CREATE /nest-demo/tsconfig.build.json (97 bytes)
CREATE /nest-demo/tsconfig.json (336 bytes)
CREATE /nest-demo/tslint.json (426 bytes)
CREATE /nest-demo/src/app.controller.spec.ts (617 bytes)
CREATE /nest-demo/src/app.controller.ts (274 bytes)
CREATE /nest-demo/src/app.module.ts (249 bytes)
CREATE /nest-demo/src/app.service.ts (142 bytes)
CREATE /nest-demo/src/main.ts (208 bytes)
CREATE /nest-demo/test/app.e2e-spec.ts (561 bytes)
CREATE /nest-demo/test/jest-e2e.json (183 bytes)
? Which package manager would you ❤️  to use? Npm
❯❯❯ Installation in progress...
CREATE /nest-demo /package.json (1721 bytes)
CREATE /nest-demo/tsconfig.build.json (97 bytes)
CREATE /nest-demo/tsconfig.json (336 bytes)
CREATE /nest-demo/tslint.json (426 bytes)
CREATE /nest-demo/src/app.controller.spec.ts (617 bytes)
CREATE /nest-demo/src/app.controller.ts (274 bytes)
CREATE /nest-demo/src/app.module.ts (249 bytes)
CREATE /nest-demo/src/app.service.ts (142 bytes)
CREATE /nest-demo/src/main.ts (208 bytes)
CREATE /nest-demo/test/app.e2e-spec.ts (561 bytes)
CREATE /nest-demo/test/jest-e2e.json (183 bytes)
? Which package manager would you ❤️  to use? Npm
✓ Installation in progress...
Successfully created project nest-demo
Get started with the following commands:
$ cd nest-demo-pro
$ npm run start
Yuppie! Now I have created a project – nest-demo in NestJS.
I will open this project into VS Code editor. It’s time to review the source code in this project.
So, now you must be wondering why all the core files are located in src. What are the usages of it? So, let me explain to you now.
app.controller.spec.ts
- It comes up with the unit tests for the controller.
app.controller.ts
- It’s a minimal controller, which consists of a single route.
app.module.ts
- It’s a root module for the application.
app.service.ts
- It has a basic service with a single method.
main.ts
- It’s an entry file of the application that utilizes the core NestFactory function. In a nutshell, it’s responsible for starting up the application instance.
Now, let’s place all your source code in the src directory. As you can see that
main.ts
is the entry point in NestJS.
Main.tsimport { NestFactory } from ‘@nestjs/core’;
import { AppModule } from ‘./app.module’;
async function bootstrap()
{
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Now, you must be wondering why we have used
NestFactory.create()
?
It’s used to create a new instance of the Nest Application. Also, the NestJS app’s root module, AppModule, is passed. Now, your NestJS app will be divided into various modules. Since we are creating a Nest app with a Root Module, each app will have a root module. Because
NestFactory.create
returns a promise; that’s why they utilized the await expression to resolve it.

Let’s Run the NestJs Application

Execute the given command to run the app.
$ npm run start:dev
Now your application is ready to run on the localhost port 3000. Visit this URL http://localhost:3000 in the web browser to view your endpoint. “Hello, World!” message will be displayed on your screen.
// app.controller.ts
@Controller()
export class AppController
{
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

The Independency of Platform

NestJs aims to be platform-independent. So, NestJs developers can write reusable logic for their project. Also, a team of developers can use the same logic for different projects as well.
Once the adaptor is generated, NestJs can function with any Node HTTP framework. However, it backs both express and fastify. So, based on the developer’s requirements, they can choose any of them.
Here, express or platform-express is the default choice for every developer. These frameworks are minimalist and have huge community support as well.
On the other side, we have got another option – platform-fastify. Fastify is a high-performance and efficient framework.
However, both the platforms come up with their own interface. These are used respectively as NestExpressApplication and NestFastifyApplication.
Anyway, let’s configure them in the given code with
app.create()
.
const app = await NestFactory.create<NestExpressApplication>(AppModule);
The
NestExpressApplication
specific methods will be exposed as part of the app object using the execution mentioned above. We don't need to declare a type unless there’s a specific method to access it.

Conclusion

Well, in this guide, I taught you some fundamentals, core files, and basic building blocks of NestJs. Also, we built a RESTful API successfully.
So, I could conclude that - I guess developers completely like the pool of tools and packages. These enhance their development performance, which leads to huge productivity. It hardly matters if you are a specialist in Angular or not, I strongly recommend giving a try on this - NestJs framework.
If you want to learn further, you can read tutorials on GitHub.
Next time, I will come up with some interesting technology or framework to consider and work on for custom application development. Until then, Happy Coding! 😉

Written by sarrahpitaliya | Avid reader and technology writer www.radixweb.com
Published by HackerNoon on 2021/09/16