Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To acquire query parameters in kebab-case using Nest JS Validation Pipe and class-transformer, you can do the following:

  1. Install the required dependencies:
npm install class-transformer class-validator
  1. Create a DTO class to define the query parameters:
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.

  1. Modify the controller method to use the validation pipe with 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.