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

admin2025-04-17  1

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);
  }
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744857228a270901.html

最新回复(0)