Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added option to use generics with the compile method #146

Merged
merged 1 commit into from
Jun 2, 2020
Merged

Added option to use generics with the compile method #146

merged 1 commit into from
Jun 2, 2020

Conversation

Gamote
Copy link
Contributor

@Gamote Gamote commented Jun 2, 2020

I've added support for generics on the compile method in order to take advantage of the Typescript validation when we are defining the schema as a param.

Usage (before):

type LoginRequest = {
  email: string;
  password: string;
};

const v = new Validator();

type CValidationSchema<T = any> = {
  $$strict?: boolean | 'remove';
  $$root?: boolean;
} & {
  [key in keyof T]: ValidationRule | undefined | any;
}

type CValidator<T> = (value: T) => true | ValidationError[];

const typedCompiler = <T>(schema: CValidationSchema<T>): CValidator<T> =>
  v.compile(schema);

const loginRequestValidator = typedCompiler<LoginRequest>({
  email: {type: 'email'},
  password: {type: 'string', empty: false, min: 6},
});

Usage (after):

type LoginRequest = {
  email: string;
  password: string;
};

const v = new Validator();

const loginRequestValidator = v.compile<LoginRequest>({
  email: {type: 'email'},
  password: {type: 'string', empty: false, min: 6},
});

I've set the T default value to any so the compile method can still be used without generics.

The most concerning part for me, regarding this commit, is that I've changed the ValidationSchema from interface to type. I've checked the code and I couldn't find any possible issue with it but I'm not totally sure about all the consequence. So please let me know if you find something.

If everything it's alright, I will continue with other PRs.

@coveralls
Copy link

Coverage Status

Coverage remained the same at 100.0% when pulling 3e5689d on Gamote:patch-1 into 22edf46 on icebob:master.

@erfanium
Copy link
Collaborator

erfanium commented Jun 2, 2020

🤔🤔🤔
Changes looks great to me. But I think extending the CheckerFunction It's not as complicated as you think. (To follow the principle of simplicity)

interface CustomCheck<T> {
   (schema: T): true | FV.ValidationError[]
}

interface Schema {
   name: string
}

const check: CustomCheck<Schema>  = validatorBase.compile({
   name: 'string'
})

@icebob icebob merged commit c2ea478 into icebob:master Jun 2, 2020
@Gamote Gamote deleted the patch-1 branch June 6, 2020 11:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants