简体   繁体   English

如何验证nestjs中的查询参数

[英]How validate query params in nestjs

Yo, i have store application with nestjs, i need validate mongo id, which is pass by query, the problem is that i also pass and search query.哟,我有使用nestjs的商店应用程序,我需要验证mongo id,这是通过查询传递的,问题是我也通过和搜索查询。 I write pipe which validate all values, and exclude this search query我写 pipe 验证所有值,并排除此搜索查询

@Injectable()
export class ValidationObjectId implements PipeTransform {
    transform(value: UniqueId, metadata: ArgumentMetadata) {
        if (
            !Types.ObjectId.isValid(value) &&
            metadata.data !== "searchString"
        ) {
            throw new BadRequestException("Неверный параметр запроса");
        }

        return value;
    }
}

But this code not reusable for other case.但是此代码不可用于其他情况。 I want get some examples, how i can do this我想要一些例子,我该怎么做

The cleanest and most reusable approach would probably be to make use of the ValidationPipe with a Query-DTO-Class.最干净和最可重用的方法可能是使用带有 Query-DTO-Class 的ValidationPipe

Take a look at the following example.看看下面的例子。

https://gitlab.com/WaldemarLehner/nestjs-swagger-example/-/tree/1aea48597ddcf93b0a0d1449fe5087413415bbee https://gitlab.com/WaldemarLehner/nestjs-swagger-example/-/tree/1aea48597ddcf93b0a0d1449fe5087413415bbee

Inside the Controller you can pass a Pipe to the @Query() -Decorator.Controller内部,您可以将 Pipe 传递给@Query() -装饰器。 You can use the ValidationPipe which already comes with Nest and makes use of the class-validator and class-transformer Packages.您可以使用 Nest 自带的ValidationPipe ,并使用class-validatorclass-transformer器包。

You can create a DTO-Class for your Query-Parameters as done in the PostHelloQuery.dto.ts from my example.您可以像我的示例中的PostHelloQuery.dto.ts中所做的那样为您的查询参数创建一个 DTO 类。

import { IsBoolean, IsOptional } from "class-validator";

class PostHelloQueryDTO {
    @IsOptional()
    @IsBoolean()
    public useExclamation?: boolean;
}

Here you define constraints for your Data using decorators from class-validator .在这里,您使用来自class-validator装饰器为您的数据定义约束。 For a list of all decorators, please refer to https://github.com/typestack/class-validator#validation-decorators .有关所有装饰器的列表,请参阅https://github.com/typestack/class-validator#validation-decorators

If none of the validators fit your needs you can also create your own Decorator as shown here .如果没有一个验证器符合您的需求,您还可以创建自己的装饰器,如下所示

In my example, the useExclamantion -Query Param is an optional boolean.在我的示例中, useExclamantion -Query 参数是可选的 boolean。 Note that incoming query parameters are parsed as strings.请注意,传入的查询参数被解析为字符串。

The conversion is done using the enableInplicitConversion -Option as seen in the Controller:转换使用enableInplicitConversion -Option 完成,如 Controller 中所示:

@Query(new ValidationPipe({
    transform: true,
    transformOptions: {enableImplicitConversion: true},
    forbidNonWhitelisted: true
}) query: PostHelloQueryDTO

For more information about using ValidationPipe with class-validator , you can take a look at the NestJS Documentation:有关将ValidationPipeclass-validator一起使用的更多信息,您可以查看 NestJS 文档:

https://docs.nestjs.com/techniques/validation https://docs.nestjs.com/techniques/validation

For your specific Use-Case (Validating MongoDB IDs), I have found an open Issue with an Example Implementation for a @IsMongoDB -Decorator:对于您的特定用例(验证 MongoDB ID),我发现了一个带有@IsMongoDB -Decorator 示例实现的未解决问题:

https://github.com/typestack/class-validator/issues/630#issuecomment-645638436 https://github.com/typestack/class-validator/issues/630#issuecomment-645638436

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM