This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
/
index.js
86 lines (72 loc) 路 2.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// @flow
import { reach } from 'yup';
import type { ValidateOptions } from 'yup';
import { ObjectSchema } from 'yup/lib/object';
import ValidationError from 'yup/lib/ValidationError';
import _get from 'lodash/get';
import _set from 'lodash/set';
import type { ValidationResultType, ValidationErrorsType } from './types';
const yupOptions: ValidateOptions = {
abortEarly: false,
};
const parseErrors = (error?: ValidationError, defaultPath: string = ''): ValidationErrorsType => {
const errors: ValidationErrorsType = {};
if (!error) {
return errors;
}
error.inner.forEach((err: ValidationError) => {
const path: string = err.path || defaultPath;
let pathErrors = _get(errors, path);
pathErrors = pathErrors || [];
pathErrors.push(err.message);
_set(errors, path, pathErrors);
});
return errors;
};
/* eslint-disable flowtype/no-weak-types */
/**
* Validate some object using Joi schema
* @param {object} obj
* @param {object} schema
* @return {object}
*/
// eslint-disable-next-line
export const validate = async function<T>(obj: T, schema: ObjectSchema<T>): Promise<ValidationResultType> {
try {
const value: T = await schema.validate(obj, yupOptions);
return {
errors: {},
value,
};
} catch (error) {
const errors: ValidationErrorsType = parseErrors(error);
return {
value: obj,
errors,
};
}
};
/**
* Validate field of the object using Joi schema
* @param {object|string} obj
* @param {string} field
* @param {object} schema
* @return {object}
*/
// eslint-disable-next-line
export const validateField = async function<T>(obj: T, field: string, schema: ObjectSchema<T>): Promise<ValidationResultType> {
const newSchema: ObjectSchema<T> = reach(schema, field);
try {
const value: T = await newSchema.validate(_get(obj, field), yupOptions);
return {
errors: {},
value,
};
} catch (error) {
const errors: ValidationErrorsType = parseErrors(error, field);
return {
value: obj,
errors,
};
}
};