DEV Community

Cover image for Default values in nestjs
Visakh Vijayan
Visakh Vijayan

Posted on • Updated on

Default values in nestjs

While passing query params in nestjs if you have come across a situation where you want the node to exist without an explicit value for it, then here is how I wasted a lot of time behind it.

import { IsNotEmpty, IsString } from "class-validator";

export class IssueSearch
{
    @IsString()
    search: string;

    @IsNotEmpty()
    length: number = 10;

    @IsNotEmpty()
    lastId: string = "0"
}
Enter fullscreen mode Exit fullscreen mode

Above is my DTO which is applied on the validation params of a controller method as below.

@Get("issues/all")
@UsePipes(new ValidationPipe({transform: true}))
async fetchAllIssues(@Query() search: IssueSearch)
{
    ...
Enter fullscreen mode Exit fullscreen mode

Hence if you access this method like
http://baseurl/controller/issues/all it will throw up an error saying it didn't find the search node.

However, if you access it like this -
http://baseurl/controller/issues/all?search=

Then it's fooled.

Let me know if there is an easier way to do this.

Top comments (1)

Collapse
 
orimdominic profile image
Orim Dominic Adah

Why not use class-validator