To acquire query parameters in kebab-case using Nest JS Validation Pipe and class-transformer, you can do the following:
npm install class-transformer class-validator
import { IsOptional, IsEnum } from 'class-validator';
import { Transform } from 'class-transformer';
enum SortOrder {
ASC = 'asc',
DESC = 'desc',
}
export class QueryParamsDto {
@IsOptional()
@Transform(({ value }) => value || SortOrder.ASC)
@IsEnum(SortOrder)
readonly sort: SortOrder;
@IsOptional()
readonly page: number;
@IsOptional()
readonly perPage: number;
}
In the above code, we define a DTO class called QueryParamsDto
which has three query parameters: sort
, page
, and perPage
. The @IsOptional()
decorator specifies that these parameters are optional.
class-transformer
:import { Controller, Get, Query, ValidationPipe } from '@nestjs/common';
import { QueryParamsDto } from './queryparams.dto';
@Controller('users')
export class UsersController {
@Get()
getUsers(@Query(new ValidationPipe({ transform: true })) queryParams: QueryParamsDto) {
// Your code here
}
}
In the above code, we use the @Query()
decorator to tell NestJS to inject the query parameters into the queryParams
argument. We also pass a new instance of ValidationPipe
with transform
option set to true
, to enable class-transformer
. This will transform the query parameter keys from camelCase to kebab-case.
With this setup, you can now receive query parameters in kebab-case in your controller method. For example, if you pass ?sort=asc&page=1&per-page=10
, queryParams.sort
will be SortOrder.ASC
, queryParams.page
will be 1
, and queryParams.perPage
will be 10
.
Asked: 2023-06-06 00:53:32 +0000
Seen: 17 times
Last updated: Jun 06 '23