Nestjs Initial setup

Pradeep R.R.
YavarTechWorks
Published in
3 min readSep 27, 2022

Nestjs is a server side nodejs framework for building efficient and reliable.It provides backend application a modular structure for organizing code into seperate modules.

First we initialize the project,

npm i -g @nestjs/cli
$nest new projectname

Our project Structure look like this,

It is inspired from angular.It was built with typescript and expressjs,which makes it compatible with the majority of express middlware.

The most important folder of the project is the src folder.Inside the src folder you can find five files in the project setup,

  • main.ts:Entry point of application.By using the NestFactory.create() method a new Nest application instance is created.
  • app.module.ts: contains the implementation of the application’s root module.
  • app.controller.ts: Contains the implementation of a basic NestJs Controller with just one route
  • app.service.ts: contains basic service implementation.
  • app.controller.spec.ts: Testing file for controller

It has the three blocks of building application

  • Controllers
  • Providers
  • Modules

Controllers

They are responsible for handling any request and returning responses to the client side of the application.if you make an API call to a particular endpoint.the controllers will receive request and returned the response.nestjs is mostly used in decorators to handle any request.

Once a controller is created,It can be added to the module nestjs can easily recognize it.

To generate a controller we use,

$nest g controller//The controller folder looks like this,import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

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

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

this method handles a HTTP GET request the @Get decorator is addedto this method.the method is using the getHello method from appservice to retrieve data and at the same time return that data as response.

Modules

The Root application module which you can find inside the app.module.ts

$nest g module //The module folder looks like this,import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

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

the object properties is passed into the @Module decorator.the three properties are:

  • imports
  • controllers
  • providers

Services

the app.service.ts,

nest g serviceimport { Injectable } from '@nestjs/common';

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

Running the application,

To start the server you give the command,

$npm run start:dev

Thank you for reading …:)

--

--