Search code examples
typescriptgraphqlclass-validatortypegraphql

GraphQL: Transform input field to pass validation (trim string value)


I'm using a class-validator package to validate a link in the GraphQL input type. The problem is that validation fails when the link contains whitespace at the end of the input string. Is there any way to trim it before validation?

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;
}

Solution

  • Custom decorator

    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,
            });
        };
    }
    

    And its usage

    @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;
    }