Logo
Section 1 / 4

NestJS 中管道概述

学习如何在 NestJS 应用程序中使用管道。

导入

NestJS 中管道概述

学习如何在 NestJS 应用程序中使用管道。

...
1 / 6

输入数据到管道

1import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; 2import { BooksService } from './books.service'; 3 4@Controller('books') 5export class BooksController { 6 constructor(private readonly booksService: BooksService){} 7 8 @Get(':id') 9 findOne(@Param('id') id: string){ 10 return this.booksService.findBookById(+id); 11 } 12}
1import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common'; 2import { BooksService } from './books.service'; 3 4@Controller('books') 5export class BooksController { 6 constructor(private readonly booksService: BooksService){} 7 8 @Get(':id') 9 findOne(@Param('id', ParseIntPipe) id: number){ 10 return this.booksService.findBookById(id); 11 } 12}

No configuration found for ID: 0225eb60d7a654c516c3441b3924a7e2b833386caa21ee718690325d0e64fe46

API 小部件

1{ 2 "statusCode": 400, 3 "message": "Validation failed (numeric string is expected)", 4 "error": "Bad Request" 5}
1npm i --save class-validator class-transformer
1import { IsString } from 'class-validator'; 2import { Language } from "../entities/books.entity"; 3 4export default class CreateBookDto { 5 @IsString() 6 title: string; 7 8 author: string; 9 publicationDate: string; 10 numberOfPages: number; 11 language: Language; 12}
1import { Body, Controller, Post, ValidationPipe } from '@nestjs/common'; 2import { BooksService } from './books.service'; 3import CreateBookDto from './dto/create-book.dto'; 4 5@Controller('books') 6export class BooksController { 7 constructor(private readonly booksService: BooksService) {} 8 9 @Post() 10 create(@Body(new ValidationPipe()) body: CreateBookDto) { 11 return this.booksService.createBook(body); 12 } 13}

No configuration found for ID: aea9050ef412b8aa5b488ef20ccb899ab4bbef56e7308dac07657c033e84544e

API 小部件

1import { Body, Controller, Post, ValidationPipe, UsePipes } from '@nestjs/common'; 2 3@Controller('books') 4export class BooksController { 5 constructor(private readonly booksService: BooksService) { } 6 7 @Post() 8 @UsePipes(new ValidationPipe()) 9 create(@Body() body: CreateBookDto) { 10 return this.booksService.createBook(body); 11 } 12 13}
1import { Body, Controller, Post, ValidationPipe, UsePipes } from '@nestjs/common'; 2 3@UsePipes(new ValidationPipe()) 4@Controller('books') 5export class BooksController { 6 constructor(private readonly booksService: BooksService) { } 7 8 @Post() 9 create(@Body() body: CreateBookDto) { 10 return this.booksService.createBook(body); 11 } 12 13}
1import { NestFactory } from '@nestjs/core'; 2import { AppModule } from './app.module'; 3import { ValidationPipe } from '@nestjs/common'; 4 5async function bootstrap() { 6 const app = await NestFactory.create(AppModule); 7 app.useGlobalPipes(new ValidationPipe()); 8 await app.listen(3000); 9} 10bootstrap();

构建 REST API

自定义管道