nest笔记七:参数校验

本文详细介绍了NestJS中使用class-validator进行参数校验的方法,包括Validator Pipe的实现,参数校验装饰器的使用,如通用、数字、日期、字符串、数组等装饰器,以及DTO与VO的应用。此外,还探讨了自定义校验装饰器的创建,并提出了关于非必传参数和未定义属性校验的疑问。
摘要由CSDN通过智能技术生成

nest笔记七:参数校验

nestjs的参数校验官方文档:https://docs.nestjs.com/techniques/validation。 它主要使用第三方的class-validator来进行参数校验。

Validator-Pipe实现

  • 网上给了很多例子,基本上可以直接拿来使用了,下面的这个是我做了一下处理的
import {
    Injectable, PipeTransform, ArgumentMetadata, ValidationError, HttpException, HttpStatus } from '@nestjs/common';
import {
    plainToClass } from 'class-transformer';
import {
    validate } from 'class-validator';

/**
 * 这是一个全局的参数验证管道,基于class-transformer
 * 如果失败,则会抛出HttpException
 * 在main.ts的nestApp要将它设为全局的
 */

@Injectable()
export class ValidationPipe implements PipeTransform {
   
    async transform(value: any, {
    metatype }: ArgumentMetadata) {
   
        if (!metatype || !this.toValidate(metatype)) {
   
            return value;
        }
        const object = plainToClass(metatype, value);
        const errors = await validate(object);
        const errorList: string[] = [];
        const errObjList: ValidationError[] = [...errors];

        do {
   
            const e = errObjList.shift();
            if (!e) {
   
                break;
            }
            if (e.constraints) {
   
                for (const item in e.constraints) {
   
                    errorList.push(e.constraints[item]);
                }
            }
            if (e.children) {
   
                errObjList.push(...e.children);
            }
        } while (true);
        if (errorList.length > 0) {
   
            throw new HttpException('请求参数校验错误:' + errorList.join(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return object;
    }

    private toValidate(metatype: Function): boolean {
   
        const types: Function[] = [String, Boolean, Number, Array, Object];
        return !types.includes(metatype);
    }
}

  • 然后在app初始化,设置全局的pipe
    const app = await NestFactory.create<NestExpressApplication>(AppModule, {
   
        logger: new 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值