npm init -y npm install @nestjs/[email protected] @nestjs/[email protected] @nestjs/[email protected] [email protected] [email protected]
Library | Description |
---|---|
@nestjs/common | Contains vast majority of functions, classes, etc, that we need from Nest |
@nestjs/core | The core runtime of NestJS that powers dependency injection, module loading, and lifecycle management |
@nestjs/platform-express | Lets Nest use Express JS for handling HTTP requests |
reflect-metadata | Helps make decorators work. Tons more on this in just a minute! |
typescript | We write Nest apps with Typescript. |
{ "compilerOptions": { "module": "commonjs", "target": "es2017", "experimentalDecorators": true, "emitDecoratorMetadata": true } }
Setting | Description |
---|---|
"experimentalDecorators": true | Enables the use of decorators (@Something) in TypeScript. Without this, NestJS decorators (like @Controller()) would throw errors. |
"emitDecoratorMetadata": true | Works together with the reflect-metadata library. Emits extra type information about classes and methods at runtime, which NestJS uses for dependency injection. |
flowchart LR A[Request] G[Response] subgraph Server direction LR B[**Pipe**<br/><br/>Validate data<br/>contained in<br/>the request] B --> C[**Guard**<br/><br/>Make sure<br/>the user is<br/>authenticated] C --> D[**Controller**<br/><br/>Route the<br/>request to a<br/>particular<br/>function] D --> E[**Service**<br/><br/>Run some<br/>business logic] E --> F[**Repository**<br/><br/>Access a<br/>database] end A --> Server direction RL Server --> G %% Define style classes classDef bigText font-size:30px; %% Apply them class A,B,C,D,E,F,G bigText
Part | Description |
---|---|
Pipes | Validates incoming data |
Guards | Handles authentication |
Controllers | Handles incoming requests |
Services | Handles data access and business logic |
Repositories | Handles data stored in a DB |
Modules | Groups together code |
Filters | Handles errors that occur during request handling |
Interceptors | Adds extra logic to incoming requests or outgoing responses |
src/main.ts
)import { Controller, Module, Get } from "@nestjs/common"; import { NestFactory } from "@nestjs/core"; @Controller() class AppController { @Get() getRootRoute() { return "hi there!"; } } @Module({ controllers: [AppController], }) class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
npx ts-node-dev src\main.ts
Nest application successfully started
localhost:3000
main.ts
function bootstrap
app.controller.ts
class AppController {}
app.module.ts
class AppModule {}
name.type_of_thing.ts
app.controller.ts
import { Controller, Get } from "@nestjs/common"; @Controller() export class AppController { @Get() getRootRoute() { return "hi there!"; } }
app.module.ts
import { Module } from "@nestjs/common"; import { AppController } from "./app.controller"; @Module({ controllers: [AppController], }) export class AppModule {}
app.controller.ts
import { NestFactory } from "@nestjs/core"; import { AppModule } from "./app.module"; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
app.controller.ts
import { Controller, Get } from "@nestjs/common"; @Controller("/app") export class AppController { @Get("/hi") getRootRoute() { return "hi there!"; } @Get("/bye") getByeThere() { return "bye there!"; } }
npm i -g @nestjs/cli
nest new project_name
npm run start:dev
nest generate module messages
import { NestFactory } from "@nestjs/core"; import { MessagesModule } from "./messages/messages.module"; async function bootstrap() { const app = await NestFactory.create(MessagesModule); await app.listen(3000); } bootstrap();
nest generate controller messages/messages --flat
--flat
says dont create folder called controllersimport { Controller, Get, Post } from "@nestjs/common"; @Controller("messages") export class MessagesController { @Get() listMessages() {} @Post() createMessage() {} @Get("/:id") getMessage() {} }
Test using Postman or Thunder Client (vscode extension) for success status code
import { Controller, Get, Post, Body, Param } from "@nestjs/common"; @Controller("messages") export class MessagesController { @Get() listMessages() {} @Post() createMessage(@Body() body: any) { console.log(body); } @Get("/:id") getMessage(@Param("id") id: string) { console.log(id); } }
Test for console log
npm install class-validator class-transformer
import { NestFactory } from '@nestjs/core'; + import { ValidationPipe } from '@nestjs/common'; import { MessagesModule } from './messages/messages.module'; async function bootstrap() { const app = await NestFactory.create(MessagesModule); + app.useGlobalPipes(new ValidationPipe()); await app.listen(3000); } bootstrap();
export class CreateMessageDto { content: string; }
+ import { IsString } from 'class-validator'; export class CreateMessageDto { + @IsString() content: string; }
How just adding dto type works?
When ts compiles to js. Type information is lost but Because of emitDecoratorMetadata in tsconfig, some of type information is also converted into javascript
import { Controller, Get, Post, Body, Param } from '@nestjs/common'; + import { CreateMessageDto } from './dtos/create-message.dto'; @Controller('messages') export class MessagesController { @Get() listMessages() {} @Post() + createMessage(@Body() body: CreateMessageDto) { console.log(body); } @Get('/:id') getMessage(@Param('id') id: string) { console.log(id); } }