Skip to content
This repository has been archived by the owner on Apr 24, 2023. It is now read-only.

Improve the typing and pipeline of validation #174

Open
Mosoc opened this issue Apr 30, 2019 · 1 comment
Open

Improve the typing and pipeline of validation #174

Mosoc opened this issue Apr 30, 2019 · 1 comment
Labels
enhancement New feature or request

Comments

@Mosoc
Copy link

Mosoc commented Apr 30, 2019

Is your feature request related to a problem? Please describe.

const ajv = new Ajv();
const validate = ajv.compile(validation);
// custom validator
const {validator, errorMessage} = validation;
const reject = message => ({error: true, message});
const validatorResult = validator && validator(value, reject);

In validation.js, we can see that it always create a new ajv instance, pass the whole validation: Object as schema to ajv.compile() to get validate function.

Then get validator: function and errorMessage: string from validation: Object by destructing assignment to follow-up action.

This mixed object and pipeline design might cause:

  • Hard to type checking and management
  • Potential risk of name conflict
  • Performance issue

Describe the solution you'd like

Use same props, but add schema property for holding ajv schema object.

    <string
      keyName="text"
      title="Text"
      validation= {{
        schema: {pattern: '^[a-zA-Z0-9]{4,10}$'} // JSONSchemaOptions
        validator: ()=>( /* ... */ ) // ValidationFunction
        errorMessage: "Error!"
      }}
    />

Describe alternatives you've considered

Use different props instead.

<string
  keyName="text"
  title="Text"
  validation={{pattern: '^[a-zA-Z0-9]{4,10}$'}}
  customizedValidator={()=>( /* ... */ )}
  errorMessage="Error!"
/>

Additional context about solution

We can get this properties by destructing assignment and create ajv instance only when schema existing.

const { schema, validator, errorMessage} = validation;
let validate = null
if(schema && !isEmpty(schema)) {
  const ajv = new Ajv();
  validate = ajv.compile(schema);
}

Typing
Also, we should complete the type definition of validation HoC.

For ajv usage, we can refer to ajv.d.ts
and keywords

And for customized validator, it will be following statement:

 validator?: (value: any) => Object  | Promise<Object>  | Promise<void> | void;
@Mosoc Mosoc added the enhancement New feature or request label Apr 30, 2019
@abz53378
Copy link
Contributor

abz53378 commented May 2, 2019

After the discussion, we think this usage is great. thanks!

 <string
      keyName="text"
      title="Text"
      validation= {{
        schema: {pattern: '^[a-zA-Z0-9]{4,10}$'} // JSONSchemaOptions
        validator: ()=>() //ValidationFunction
        errorMessage: "Error!"
      }}
    />

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants