loading...

Default values in nestjs

vjnvisakh profile image Visakh Vijayan ・1 min read

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"
}

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)
{
    ...

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.

Posted on by:

vjnvisakh profile

Visakh Vijayan

@vjnvisakh

Willing to learn anything and everything exciting. Always awake. Skips food for fun.

Discussion

pic
Editor guide