首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GraphQL:转换输入字段以通过验证(修剪字符串值)

GraphQL:转换输入字段以通过验证(修剪字符串值)
EN

Stack Overflow用户
提问于 2020-12-13 19:23:14
回答 1查看 269关注 0票数 1

我正在使用一个class-validator包来验证GraphQL输入类型中的链接。问题是,当链接在输入字符串的末尾包含空格时,验证会失败。有没有办法在验证前对其进行修剪?

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-23 17:14:51

自定义装饰器

代码语言:javascript
复制
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,
        });
    };
}

及其用法

代码语言:javascript
复制
@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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65275030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档