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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-06 00:53:32 +0000
Seen: 15 times
Last updated: Jun 06 '23
Why am I not getting a response when making a URL call in ASP.NET Web API?
How to provide parameters to machine learning model objects?
How can you obtain several parameters using a single GET request?
How can Rails be configured to allow one key and require another using strong parameters?
What is the process of creating global parameters in OpenAPI?
How can I include custom header parameters in request details when using swagger?
What are some queries regarding the simulation of pic_poll_read in kvm?
How to pass parameter correctly from @Url.Action to method?
Explain what the main file is, but do not give any details about the parameters it contains.