![](/img/trans.png)
[英]NestJS DTO Decorators with InterestionType/PickType still enforcing isDefined() validation when field should be optional
[英]DTO Optional during the PATCH call
我有一個 DTO 來驗證來自創建我的實體的POST
請求的數據。
我希望在PATCH
請求期間使用“相同”的 DTO 來更新我的實體,但某些字段需要是可選的。
我嘗試使用 Partial,但那樣我就錯過了一些重要的控制。 我不能使用@ValidateIf
因為我沒有屬性來檢測它是POST
還是PATCH
。
我不能使用 Extends,因為我需要用@IsOptional
覆蓋每個屬性
是否可以使用“ createDTO
”來更新實體,而不復制它並重命名為“ updateDTO
”僅用於添加@IsOptional
屬性?
我認為您可以通過兩種方式實現這一目標:
ValidateIf
與注入的屬性一起使用,例如。@Injectable()
export class HttpMethodInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler
): Observable<any> {
const req = context.switchToHttp().getRequest();
req.body.httpMethod = req.method;
return next.handle();
}
}
export class TestDto {
@IsNotEmpty()
@IsString()
public property: string;
@IsNotEmpty()
@IsString()
@ValidateIf(o => o.httpMethod === 'POST')
public otherProperty: string;
@IsString()
public httpMethod: string;
}
groups
將方法作為每個 function 的值傳遞,並在裝飾器上傳遞預期值,例如: @Post()
@UsePipes(new ValidationPipe({ groups: ['post'] }))
public create(@Body() body: TestDto): Promise<any> {
return;
}
@Patch()
@UsePipes(new ValidationPipe({ groups: ['patch'] }))
public update(@Body() body: TestDto): Promise<any> {
return;
}
export class TestDto {
@IsNumberString(null, { groups: ['post'] }) //This validation will only apply if group has post in it, so on patch it will do nothing
public test: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.