Installation Nest JS
$ npm i -g @nestjs/cli
$ nest new project-name
Alternatives Way To Install Nest JS
$ git clone https://github.com/nestjs/typescript-starter.git project
$ cd project
$ npm install
$ npm run start
Decorators In NestJS
┌───────────────────────┬──────────────────┬──────────────────────────────┐
│ Type │ Example │ Use Case │
├───────────────────────┼──────────────────┼──────────────────────────────┤
│ Class Decorators │ @Controller() │ Defines controllers & modules │
│ Method Decorators │ @Get(), @Post() │ Handles HTTP requests │
│ Property Decorators │ @Inject() │ Injects dependencies │
│ Parameter Decorators │ @Param(), @Body()│ Extracts request data │
│ Custom Decorators │ @Log() │ Adds reusable logic │
└───────────────────────┴──────────────────┴──────────────────────────────┘
constrollers
controllers can handel the incoming requests
and sending to the response to the clint
Example for to create simple API using Controller and Get Decorator
import {Controller, Get} from '@nestjs/common';
@Controller('all-students')
export class allStudents(){
@Get()
findAllStudents():string{
return "This is All Students Response"
}
}
Providers In NestJs
In NestJs Provider is a class that can be Injected into other classes using Dependency Injection (ID)
Example user.service.ts
import {Injectable} from '@nestjs/common';
@Injectable()
export class UserService{
private users=[
{id:1,name:"Aishwary"},
{id:2,name:"Harsh"},
{id:3,name:"Ambuj"},
{id:4,name:"Somyadeb"},
{id:5,name:"Shubham"},
{id:6,name:"Anish"}
];
getUserById(id:number){
return this.user.find(user=>user.id===id);
}
}
Example user.controller.ts
import {Controller,Get,Param} from '@nestjs/common';
import {UserService} from './user.service';
export class UserController{
constructor(private readonly userService:UserServivce){}
@Get('user')
getUser(@Param(':id')id:string){
return this.userService.getUserById(Number(id));
}
}
Example user.module.ts
import {module} from '@nestjs/common';
import {UserSerive} from './user.service';
import {UserController} from './uer.controller';
@Module({
controllers:[UserController],
providers:[Userservice],
)}
export class UserModule {}
Example app.module.ts
import {Module} from '@nestjs/common';
import {UserModule} from './user/user.module';
@Module({
import:[UserModule],
})
export class AppModuel{}
Top comments (0)