繁体   English   中英

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

[英]How to validate if a Param string is a MongoId in Nestjs without DTO

我的 controller 中有请求,@Param 是@Param的字符串版本。 如果我使用无效的字符串格式(不匹配 MongoId 格式)调用此请求,则请求将一直执行,直到 MongoDB 调用引发内部服务器错误。

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

当前 Controller 端点:

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

被调用的服务:

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

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

    if (!niceResult) {
      throw new NotFoundException()
    }
    return table
  }

答案是使用自定义验证 pipe:

创建 pipe 并将其导出:

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{
      if(ObjectId.isValid(value)){
          if((String)(new ObjectId(value)) === value)
              return value;        
          throw new BadRequestException
      }
      throw new BadRequestException
  
  };
}

使用 controller 中的 pipe 来验证字符串

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

Alternatively you could change the returntype in the pipe from string to ObjectId if you are using mongoDB instead of mongoose, mongoose supports requests witht he id in a string format

nestjs中使用类验证器

通过使用 @IsMongoIdObject()
像这样:

   class ParamDTO{
@IsMongoIdObject()   
id:string
}

----你的功能---

@Get(':id')
  @ApiOperation({ summary: 'Get nice information' })
  findOne(
    @Param() id: ParamDTO) {
    return this.niceService.findOne(id.id);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM