(NestJS -1) Introduction to NestJS (2024)

(NestJS -1) Introduction to NestJS (2)

This series will provide you with a step-by-step guide to setting up a NestJS application, from the basics to a production-ready project. We will explore the core elements of NestJS, how they work together, and walk you through a straightforward example to kick-start your project. This comprehensive guide will help you build a solid foundation and advance towards creating robust, production-grade applications.

In this article, we will give a general outline of constructing a basic NestJS application. We will look into the fundamentals of each element, their collaboration, and guide you through a straightforward example to kick-start your project. To make this series more practical and relatable, we will use an e-commerce application as our example throughout the guide.

Prerequisites

Before beginning, you should have a basic understanding of TypeScript, JavaScript, Express.js, and some Object-Oriented Programming (OOP) concepts like classes, objects, interfaces, and inheritance.

NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It uses TypeScript by default and is heavily inspired by Angular, leveraging its modular architecture and dependency injection patterns. It is built with and fully supports TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

  • TypeScript: Enjoy the benefits of a strongly typed language, which can catch errors early in the development cycle.
  • Modularity: Organize code in modules to enhance reusability and scalability.
  • Dependency Injection: Manage your dependencies effectively and write testable, maintainable code.
  • Out-of-the-Box Support: Get robust support for common functionalities like validation, database integration, Exception handling, logging services and more.

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (version >= 16)
  • npm (comes with Node.js)
  • Code editor (VSCode recommended)

Installation NestJS CLI

We need to install the NestJS CLI globally, To create and manage NestJS projects. Use below command to install:

npm install -g @nestjs/cli

Open Command Prompt and navigate to your working directory before starting the project creation process.

cd <path to your working directory>
//exmaple $ cd Desktop

You can create the NestJS application in 2 ways mainly:

1. Create Using CLI

NestJS provides a command to create a basic application with some setup files and a src folder:

nest new project-name

Nestjs support different package manager(npm recommended)

2. Clone from Git

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

Replace “project-name” with the desired name for your project.

A typical NestJS project structure looks like this:

(NestJS -1) Introduction to NestJS (3)
  • src: Holds all the resource files of application.
  • app.controller.ts: Handles incoming requests and returns responses.
  • app.service.ts: Contains business logic.
  • app.module.ts: The root module that ties everything together.
  • main.ts: The entry point of the application.
  • .spec.ts: These are testing file.
  • package.json: It contains metadata about the project, as well as information about the dependencies, scripts, and various other configurations.
  • .json: These are config files.

In NestJS we mostly working with the files like Root Module, User Modules, Controllers and Services.

Nest is built around a language feature called decorators. we mostly use classes and decorators. In order to better understand how it works I recommend to read this article

Main File

The main.ts file contains a aync funtion, which will bootstrap the application.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap()

The NestFactory is used to create a application instance using the create method which return’s a “NestApplication” object.

Module

The root module, often named AppModule by convention, serves as the entry point of your NestJS application. It is responsible for bootstrapping the application, configuring the dependency injection container, and organizing the application's features into cohesive units called modules. A module is a class annotated with a @Module() decorator.

Here’s a how controllers in NestJS looks:

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

@Module({
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

To create a controller using the CLI, simply execute the $ nest g module [name] command.

Controller

Controllers in NestJS play a crucial role in handling incoming HTTP requests like Get, Post, Put, Delete and sending back responses to clients. They act as intermediaries between incoming requests and the business logic of your application, typically implemented in services. In the following example we’ll use the @Controller() decorator, which is required to define a basic controller. It allows us to easily group a set of related routes, and minimize repetitive code. It takes a name to define a group of related routers.

Here’s a how controllers in NestJS looks:

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

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('') // it defines http get request
getHello(): string {
return this.appService.getHello();
}
}

There are other decorators which we use in controllers, they are Post, Put,Patch, Get, Delete. It takes a name to easily identify the router.

The controllers are mainly used to handle user requests and check if the user has Authority to access thatservice. Its main functionality is used to accept the request and return the response. We don’t write any logic in controllers.

We mostly use asynchronous function to handle multiple requests simultaneously, async / await keeps our asynchronous code organized and more readable.

To create a controller using the CLI, simply execute the $ nest g controller [name] command.

Service

A service in NestJS is a class that encapsulates reusable business logic and can be injected into other components, such as controllers or other services, using dependency injection. Services promote code reuse, maintainability, and test ability by separating concerns and keeping controllers lean. This service will be responsible for data storage and retrieval, and is designed to be used by the controllers. In the following example we’ll use the @Injectable() decorator, It marks a class as a provider that can be injected into other components, such as controllers, other services, or modules.

Here’s a how controllers in NestJS looks:

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

The service will act as a layer between database and controller.

To create a controller using the CLI, simply execute the $ nest g service [name] command.

CRUD Generate

In applications, we often build various features to meet business requirements. To do this, we need to create CRUD files to implement the business logic. We have discussed how to create each resource file in the above section.

To reduce the repetitive process of creating these files manually, the NestJS CLI provides a command to generate all the basic required resource files at once:

$ nest g resource [name]

This command generates a folder with the given name, It includes several files, such as module.ts, service.ts, controller.ts, as well as testing files (.spec files).

Additionally, it creates an entity folder with an entity.ts file extension and a DTO (Data Transfer Object) folder with some dto.ts file extension.

The Entity files are used to define the data structure of a database table and DTO files are used to define the structure of income and outgoing data.

Now, start the application in the terminal or command prompt using the command below in the root directory path. This command will start the HTTP server on the port you have defined in the src/main.ts file:

$ npm run start

we have another command which will watch the file changes in the application and reload it on save:

$ npm run start:dev

If application is running, the application will run on HTTP server on localhost Ip on the given port number in app/main.ts file.

(NestJS -1) Introduction to NestJS (4)

You can see the log in console like above. Now you can test your application in different ways like postman, web browser, VScode extensions and soon.

Option 1: Using Postman Application

If you already have Postman installed, open it. If not, you can download it from the official Postman website.

  • Click on the + button to open a new tab.
  • Select the Request type as get and enter the request url http://localhost:3000 in request box.
  • Click the Send button. It will send the request to the given url and display the response in the response section. Our application response should be Hello World!
(NestJS -1) Introduction to NestJS (5)

Option 2: Using Extensions in VSCode

You can also use Postman-like extensions in VSCode for API testing, such as Postman or Thunder Client. Here's how you can set it up:

  • Open VSCode.
  • Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X.
  • Search for Thunder Client and click Install.
  • Open the extension from the sidebar.
  • Click on New Request from the sidebar. Select the Request type as get and enter the request url http://localhost:3000 in request box.
  • Click the Send button. The response should be Hello World!
(NestJS -1) Introduction to NestJS (6)

Option 3: using web browser

Open the new tab in the browser and navigate to the url http://localhost:3000. The response should be Hello World!

Note: The web browsers can be used for get only requests which do not require any authentication or Authorization to access.

For more in details please refer to official documentation

In this article, we covered the basics of setting up a NestJS project using either the NestJS CLI or by cloning a starter repository. We explored the fundamental building blocks of a NestJS application, including modules, controllers, and services.

By following this guide, you should now have a solid foundation for starting your own NestJS projects.

Check out the next article to learn about configuring custom config module.

If you found this article useful, please consider leaving a clap (👏) and a comment.

Thanks for reading this far! Happy coding with NestJS!

(NestJS -1) Introduction to NestJS (2024)
Top Articles
Use mobile data on your iPhone or iPad – Apple Support (UK)
How to avoid data roaming charges on your iPhone
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 5496

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.