我的控制器中有請求,這@Param是 MongoId 的字串版本。如果我使用無效的字串格式呼叫此請求,而不是匹配 MongoId 格式,則請求會一直執行,直到 MongoDB 呼叫引發內部服務器錯誤。
我如何驗證例如"aaa"“ANWPINREBAFSOFASD”未驗證并在我的請求中盡早停止
當前控制器端點:
@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
}
uj5u.com熱心網友回復:
對此的答案是使用自定義驗證管道:
創建管道并將其匯出:
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
};
}
使用控制器中的管道來驗證字串
@Get(':id')
@ApiOperation({ summary: 'Get nice information' })
findOne(
@Param('id', ValidateMongoId) id: string) {
return this.niceService.findOne(id);
}
或者,如果您使用的是 mongoDB 而不是 mongoose,您可以將管道中的 returntype 從 string 更改為 ObjectId,mongoose 支持帶有字串格式的 id 的請求
uj5u.com熱心網友回復:
在nestjs 中使用類驗證器
通過
像這樣使用@IsMongoIdObject() :
class ParamDTO{
@IsMongoIdObject()
id:string
}
----您的職責---
@Get(':id')
@ApiOperation({ summary: 'Get nice information' })
findOne(
@Param() id: ParamDTO) {
return this.niceService.findOne(id.id);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/387325.html
標籤:javascript MongoDB 验证 猫鼬 嵌套
