javascript - How to validate if a Param string is a MongoId in Nestjs without DTO - Stack Overflow

I have requests in my controller, the @Param is the string version of the MongoId.If I call this reque

I have requests in my controller, the @Param is the string version of the MongoId. 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.

How do I validate that for example "aaa" or "ANWPINREBAFSOFASD" is not validated and stops as early as possible in my requests

Current Controller Endpoint:

@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
  }

I have requests in my controller, the @Param is the string version of the MongoId. 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.

How do I validate that for example "aaa" or "ANWPINREBAFSOFASD" is not validated and stops as early as possible in my requests

Current Controller Endpoint:

@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
  }
Share edited Dec 12, 2021 at 10:07 Branchverse asked Dec 11, 2021 at 15:19 BranchverseBranchverse 1,3971 gold badge10 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The answer to this is to use a custom Validation pipe:

Create the pipe and export it:

import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from "@nestjs/mon";
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
  
  };
}

Use the pipe in the controller to validate the string

@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

use class-validator in nestjs

by using @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);
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744857226a4597480.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信