#class-validator query param dependencies

1 messages · Page 1 of 1 (latest)

blissful tapir
#

Take this code for example


export enum Options {
  USERS = 'users',
  ADMINS = 'admins',
}

export class QueryDTO {
  @IsDefined()
  @Validate(IsValidOptionType)
  readonly filter: Options;

  @IsOptional()
  @Transform((value) => Number(value))
  readonly userId: string;

  @IsOptional()
  @Transform((value) => Number(value))
  readonly adminId: string;
}

Goal is to only allow the query to run by sets, meaning, if filter = users then userId needs to exist, if filters = admins then adminId needs to exist, and ignore the other params.

Whats a good way to validate this? I would really love something like this

@Validate(Dependency['users'])
@IsOptional()
@Transform((value) => Number(value))
readonly userId: string;
fair edge
blissful tapir
#

I tried that but its not working

#

If filter = users and I do

@IsOptional()
@ValidateIf(o => o.filter === 'users')
  @Transform((value) => Number(value))
  readonly userId: string;

userId is NaN

fair edge
#

Got a reproduction of it not working?

blissful tapir
#

Em, no let me see if i can make a codesandbox

#

Eh, not building at all

#

Ill keep trying

main falcon
#

Why not have a single "id" instead of two different ones?

#

Be careful using annotations to do what could be considered "business logic".

#

Anyway, you could use groups..

#
import { IsEnum, IsString, validate } from 'class-validator';

enum Options {
    USERS = 'users',
    ADMINS = 'admins'
}

class Conditional {
    @IsEnum(Options)
    public filter: Options;

    @IsString({ groups: [ 'users' ] })
    public requiredForUsers: string;

    @IsString({ groups: [ 'admins' ] })
    public requiredForAdmins: string;

    public constructor(obj: Partial<Conditional>) {
        Object.assign(this, obj);
    }
}

(async () => {
    console.log(await validate(new Conditional({
        filter: Options.USERS
    }), {
        groups: [ 'users' ]
    }));

    console.log(await validate(new Conditional({
        filter: Options.ADMINS
    }), {
        groups: [ 'admins' ]
    }));
})();