天天看點

nest pipes自定義管道練習

custom pipes

import { PipeTransform, Injectable, ArgumentMetadata } from "@nestjs/common"

// ArgumentMetadata類型定義
export interface ArgumentMetadata {
  type: 'body' | 'query' | 'param' | 'custom';
  metatype?: Type<unknown>;
  data?: string;
}

@Injectable()
export class ValidationPipe implements PipeTransform {
	transform(
		value: any,
		metadata: ArgumentsMetaData
	) {
		return value
	}
}
           

validation.pipe

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
// class-validator class-transformer 是同一個作者産出的

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }
    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }

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

DTO

import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
  @IsString()
  name: string;

  @IsInt()
  age: number;

  @IsString()
  breed: string;
}
           

Controller

@Post()
async create(
  @Body(new ValidationPipe()) body: CreateCatDto,
) {
  this.catsService.create(body);
}
           

全局使用管道

import { Module } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_PIPE, // 依賴注入
      useClass: ValidationPipe,
    },
  ],
})
export class AppModule {}
           

class-validator