Hi i have nest app dto:
export class TestDto {
@IsNotEmpty()
id: number;
@IsNotEmpty()
slug: string;
@IsNotEmpty()
size: number;
}
and Post request:
@Post(':id/start')
async startTest(
@Param('id') id: number,
@Request() req,
@Body() testDto?: TestDto
): Promise<RoomDto | string> {
return await this.roomsService.startTest(id, testDto);
}
I want to have testDto from body optional but instead i have an error when sending request:
{
"statusCode": 400,
"message": [
"slug should not be empty",
"size should not be empty"
],
"error": "Bad Request"
}
How to achieve something like this?
Hi i have nest app dto:
export class TestDto {
@IsNotEmpty()
id: number;
@IsNotEmpty()
slug: string;
@IsNotEmpty()
size: number;
}
and Post request:
@Post(':id/start')
async startTest(
@Param('id') id: number,
@Request() req,
@Body() testDto?: TestDto
): Promise<RoomDto | string> {
return await this.roomsService.startTest(id, testDto);
}
I want to have testDto from body optional but instead i have an error when sending request:
{
"statusCode": 400,
"message": [
"slug should not be empty",
"size should not be empty"
],
"error": "Bad Request"
}
How to achieve something like this?
Share Improve this question asked Feb 9, 2021 at 15:35 Dawid KwiatońDawid Kwiatoń 1672 silver badges15 bronze badges1 Answer
Reset to default 4You have to change the IsNotEmpty decorator to IsOptional, when you add the question mark to a parameter you're telling Typescript that that value can be undefined and that doesn't matter in the running time.
You can check the allowed decorators here: https://github./typestack/class-validator#validation-decorators
The result DTO will be something like this:
export class TestDto {
@IsNotEmpty()
id: number;
@IsOptional()
slug?: string;
@IsOptional()
size?: number;
}
Remember to import IsOptional from class-validator package.