Skip to content

feature: add parameter type map for decorators #2502

Open
@leandroluk

Description

@leandroluk

Description

Hello, I'm using the lib to validate some projects and I have an interesting feature to centralize validation settings for certain fields. See:

import * as classValidator from 'class-validator';
import {Field, InputType} from '@nestjs/graphql';
import {IsEmail, IsNotEmpty, IsString, MinLength} from 'class-validator';

export namespace ClassValidator {
  type AllKeys = keyof typeof classValidator
  type Func = (...args: any) => any
  type DecoratorKeys = {[Key in AllKeys]: typeof classValidator[Key] extends Func ? Key : never;}[AllKeys];
  export type ParameterMap = {[Key in DecoratorKeys]: Parameters<typeof classValidator[Key]>;};
  export type FieldMap = Record<string, Partial<ParameterMap>>
}

const fields: ClassValidator.FieldMap = {
  email: {
    IsNotEmpty: [{message: "'email' cannot be empty."}],
    IsEmail: [{}, {message: "'email' is invalid."}],
  },
  password: {
    IsNotEmpty: [{message: "'password' cannot be empty."}],
    IsString: [{message: "'password' must be a string."}],
    MinLength: [8, {message: "'password' must have at least 8 characters."}],
  },
  token: {
    IsNotEmpty: [{message: "'token' cannot be empty."}],
  },
  code: {
    IsNotEmpty: [{message: "'code' cannot be empty."}],
  },
};

With this i can share the same field configuration between decorators and maybe it can be useful to more people.

Proposed solution

Add the namespace ClassValidator or something like that in default library types

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions