如何在没有DTO的情况下验证Nestjs中的Param字符串是否为MongoId

Bra*_*rse 2 javascript validation mongoose mongodb nestjs

我的控制器中有请求,这@Param是 MongoId 的字符串版本。如果我使用无效的字符串格式(不匹配 MongoId 格式)调用此请求,则该请求将继续执行,直到 MongoDB 调用抛出内部服务器错误。

我如何验证例如"aaa"“ANWPINREBAFSOFASD”未经过验证并在我的请求中尽早停止

当前控制器端点:

@Get(':id')
  @ApiOperation({ summary: 'Get nice information' })
  findOne(
    @Param('id') id: string) {
    return this.niceService.findOne(id);
  }
Run Code Online (Sandbox Code Playgroud)

该服务称为:

async findOne(id: string): Promise<NiceDocument> {

    const niceResult: NiceDocument = await this.NiceSchema.findById(id)

    if (!niceResult) {
      throw new NotFoundException()
    }
    return table
  }
Run Code Online (Sandbox Code Playgroud)

Bra*_*rse 6

答案是使用自定义验证管道:

创建管道并将其导出:

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

@Injectable()
export class ValidateMongoId implements PipeTransform<string> {
  transform(value: string, metadata: ArgumentMetadata): string{ // Optional casting into ObjectId if wanted!
      if(ObjectId.isValid(value)){
          if((String)(new ObjectId(value)) === value)
              return value;        
          throw new BadRequestException
      }
      throw new BadRequestException
  
  };
}
Run Code Online (Sandbox Code Playgroud)

使用控制器中的管道来验证字符串

@Get(':id')
  @ApiOperation({ summary: 'Get nice information' })
  findOne(
    @Param('id', ValidateMongoId) id: string) {
    return this.niceService.findOne(id);
  }
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用 mongoDB 而不是 mongoose,则可以将管道中的返回类型从 string 更改为 ObjectId,mongoose 支持字符串格式的 id 请求