Phil
Phil

Reputation: 7566

Node.JS: How do you validate QueryParams in routing-controllers?

lets say you have an interface like this:

import { Get, QueryParam } from 'routing-controllers';
// ...
@Get('/students')
async getStudents(
    @QueryParam('count') count?: number,
): Promise<void> {
    console.log(count);
}

How do you ensure count is an int and not a float, for example? Something like this is not valid:

@IsInt() @QueryParam('count') count?: number,

IsInt can only be used on a class property, eg for a body model, not for a single parameter value. But according to. this https://github.com/typestack/routing-controllers#auto-validating-action-params it is possible:

This technique works not only with @Body but also with @Param, @QueryParam, @BodyParam and other decorators.

Upvotes: 1

Views: 4157

Answers (1)

Phil
Phil

Reputation: 7566

I had missed this in the docs: https://github.com/typestack/routing-controllers#inject-query-parameters By injecting all of the QueryParams instead of individual QueryParam, you can validate them as a class model:

enum Roles {
    Admin = "admin",
    User = "user",
    Guest = "guest",
}

class GetUsersQuery {

    @IsPositive()
    limit: number;

    @IsAlpha()
    city: string;

    @IsEnum(Roles)
    role: Roles;

    @IsBoolean()
    isActive: boolean;

}

@Get("/users")
getUsers(@QueryParams() query: GetUsersQuery) {
    // here you can access query.role, query.limit
    // and others valid query parameters
}

Also, make sure you don't use barrel-imports to import Enums, or open-api-generator will produce an error that the enum is undefined and not and object; eg avoid this: import { Roles } from '../..'

Upvotes: 0

Related Questions