简体   繁体   English

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

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

I have requests in my controller, the @Param is the string version of the MongoId.我的 controller 中有请求,@Param 是@Param的字符串版本。 If I call this request with an invalid format of the string, not Matching the MongoId format, the request goes through until the MongoDB call throws an internal server Error.如果我使用无效的字符串格式(不匹配 MongoId 格式)调用此请求,则请求将一直执行,直到 MongoDB 调用引发内部服务器错误。

How do I validate that for example "aaa" or "ANWPINREBAFSOFASD" is not validated and stops as early as possible in my requests如何验证例如"aaa"或“ANWPINREBAFSOFASD”未验证并在我的请求中尽早停止

Current Controller Endpoint:当前 Controller 端点:

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

The service that is called:被调用的服务:

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

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

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

The answer to this is to use a custom Validation pipe:答案是使用自定义验证 pipe:

Create the pipe and export it:创建 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
  
  };
}

Use the pipe in the controller to validate the string使用 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 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

use class-validator in nestjsnestjs中使用类验证器

by using @IsMongoIdObject()通过使用 @IsMongoIdObject()
like this:像这样:

   class ParamDTO{
@IsMongoIdObject()   
id:string
}

----Your Funcation--- ----你的功能---

@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