【问题标题】:GraphQL: Transform input field to pass validation (trim string value)GraphQL:转换输入字段以通过验证(修剪字符串值)
【发布时间】:2021-03-24 06:24:21
【问题描述】:

我正在使用class-validator 包来验证 GraphQL 输入类型中的链接。 问题是当链接在输入字符串的末尾包含空格时验证失败。 有什么方法可以在验证之前对其进行修剪吗?

import { InputType, Field, Int } from 'type-graphql';
import { IsUrl, IsOptional } from 'class-validator';
import { Project } from '../entities';

@InputType()
export default class UpdateProjectInput implements Partial<Project> {
    @Field(type => Int)
    id: number;

    @Field({ nullable: true })
    @IsUrl({}, { message: 'Link is not a valid url' })
    @IsOptional()
    link?: string;
}

【问题讨论】:

    标签: typescript graphql class-validator typegraphql


    【解决方案1】:

    自定义装饰器

    export default function Transform(
        cb: (value: any) => any
    ): (target: Object, propertyKey: string | symbol) => void {
        return function (target: Object, propertyKey: string | symbol) {
            Object.defineProperty(target, propertyKey, {
                set(value) {
                    this.value = cb(value);
                },
                enumerable: true,
                configurable: true,
            });
        };
    }
    

    及其用法

    @InputType()
    export default class UpdateProjectInput implements Partial<Project> {
        @Field(type => Int)
        id: number;
    
        @Field({ nullable: true })
        @Transform(value => value?.trim())
        @IsUrl({}, { message: 'Link is not a valid url' })
        @IsOptional()
        link?: string;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2018-07-20
      • 2021-12-07
      相关资源
      最近更新 更多