Nestjs中的管道

发布于 5 年前 作者 phonegap100 1740 次浏览 来自 分享

一、关于Nestjs中的管道

文档: https://docs.nestjs.com/pipes

通俗的讲:Nestjs中的管道可以将输入数据转换为所需的输出。此外,它也可以处理验证,当数据不正确时可能会抛出异常。

二、Nestjs中创建和使用管道

1、创建管道

nest g pipe user

管道创建完成后生成如下代码:


import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
@Injectable()
export class UserPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
//这个里面可以修改传入的值以及验证转入值的合法性
    return value;
  }
}

2、使用管道

import { Controller,Get,UsePipes,Query} from '@nestjs/common';
import {UserPipe} from '../../user.pipe';
@Controller('user')
export class UserController {    
    @Get()
    index(){
        return '用户页面';
    }
    @Get('pipe')
    @UsePipes(new UserPipe())
    pipe(@Query() info){
        console.log(info);
        return `this is Pipe`;
    }
}

三、Nestjs中管道结合Joi库实现数据验证

Joi库: https://github.com/hapijs/joi


import { ArgumentMetadata, Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import * as Joi from '@hapi/joi';
@Injectable()
export class InfoPipe implements PipeTransform {
  constructor(private readonly schema) { }
  async transform(value: any, metadata: ArgumentMetadata) {
    console.log(value);
    
    const { error } = Joi.validate(value, this.schema)
    if (error) {
      throw new BadRequestException('发送语义有误')
    }
    return value;
  }
}
import * as Joi from '@hapi/joi';

let rootInfo = Joi.object().keys({
  name: Joi.string().required(),
  age: Joi.number().integer().min(6).max(66).required(),
})
@Get()
@UsePipes(new InfoPipe(rootInfo))
root(@Query() info) {
    return `hello world`;
}
回到顶部