内置

Nest comes with nine pipes available out-of-the-box:Nest 附带九个开箱即用的管道:

They're exported from the @nestjs/common package.它们是从 @nestjs/common 包中导出的。

@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
  return this.catsService.findOne(id);
}

自定义(处理参数是字符串,或者字段对象是字符串的情况)

兼容json传参,raw 传参,json 为字符串传参

nestjs @body if data is string type, use json parse

nestjs@body如果数据是字符串类型,则使用json解析

import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common';

@Injectable()
export class ParseJsonPipe implements PipeTransform {
    transform (value: any, metadata: ArgumentMetadata) {
        if (typeof value === 'string') {
            if ((value.startsWith('\\'') && value.endsWith('\\'')) || (value.startsWith('"') && value.endsWith('"'))) {
                value = value.slice(1, -1);
            }
            try {
                return JSON.parse(value);
            } catch (error) {
                // 处理JSON解析错误
                throw new BadRequestException('无效的JSON数据');
            }
        } else if (typeof value === 'object') {
            for (const key in value) {
                const originValue = value[key];
                // value string 类型进行解析
                if (typeof originValue === 'string') {
                    try {
                        const changeAfterValue = JSON.parse(value[key]);
                        if (typeof changeAfterValue === 'number') {
                            continue;
                        }
                        value[key] = changeAfterValue;
                    } catch (e) {
                        value[key] = originValue;
                    }
                }
            }
        }
        return value;
    }
}