乐闻世界logo
搜索文章和话题

How validate query params in nestjs

1个答案

1

NestJS leverages the powerful Pipes concept to handle validation logic, allowing you to apply validation rules declaratively. For validating query parameters, you typically use the class-validator and class-transformer libraries, which enable you to specify validation rules through Data Transfer Objects (DTOs).

Step 1: Install Required Packages

First, install the class-validator and class-transformer packages. If not already installed, use the following command:

bash
npm install class-validator class-transformer

Step 2: Create DTO and Add Validation Rules

Next, create a DTO to define and validate query parameters. You can use decorators provided by class-validator to add validation rules.

typescript
import { IsInt, IsOptional, IsString, Min } from 'class-validator'; export class GetItemsQueryDto { @IsOptional() @IsString() search?: string; @IsOptional() @IsInt() @Min(0) skip?: number; @IsOptional() @IsInt() @Min(1) limit?: number; }

In this example, we define three optional query parameters: search (string type), skip (integer type, must be greater than or equal to 0), and limit (integer type, must be greater than 1).

Step 3: Apply DTO to Request Handling Function

In your controller, you can use the @Query() decorator to automatically apply the DTO and trigger validation logic.

typescript
import { Controller, Get, Query, UsePipes, ValidationPipe } from '@nestjs/common'; @Controller('items') export class ItemsController { @Get() @UsePipes(new ValidationPipe({ transform: true })) getItems(@Query() query: GetItemsQueryDto) { // Here, query is already validated // You can safely use query.search, query.skip, and query.limit // ... } }

In the @UsePipes(new ValidationPipe({ transform: true })) decorator, the transform: true option ensures that query parameters from the request are converted to the data types defined in the DTO and validated.

If query parameters are invalid, NestJS automatically returns a 400 (Bad Request) response along with detailed error information, allowing frontend developers to clearly identify which parameters do not meet the requirements.

Example

Suppose we have an endpoint to retrieve a list of items that accepts search (for fuzzy querying item names), skip, and limit (for pagination) query parameters. Using the above DTO and controller configuration, if a user sends a request like GET /items?search=phone&skip=-1&limit=5, NestJS will return a 400 response with an error indicating that the skip parameter must be greater than or equal to 0.

This is how to validate query parameters in NestJS. By leveraging NestJS's Pipes and class-validator, you can easily add complex validation logic to any route.

2024年6月29日 12:07 回复

你的答案