-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathvalidateUtil.ts
More file actions
249 lines (213 loc) · 6.86 KB
/
validateUtil.ts
File metadata and controls
249 lines (213 loc) · 6.86 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import RawAsyncValidator from 'async-validator';
import * as React from 'react';
import warning from 'rc-util/lib/warning';
import type {
InternalNamePath,
ValidateOptions,
RuleObject,
StoreValue,
RuleError,
} from '../interface';
import { defaultValidateMessages } from './messages';
import { setValues } from './valueUtil';
// Remove incorrect original ts define
const AsyncValidator: any = RawAsyncValidator;
/**
* Replace with template.
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template: string, kv: Record<string, string>): string {
return template.replace(/\$\{\w+\}/g, (str: string) => {
const key = str.slice(2, -1);
return kv[key];
});
}
async function validateRule(
name: string,
value: StoreValue,
rule: RuleObject,
options: ValidateOptions,
messageVariables?: Record<string, string>,
): Promise<string[]> {
const cloneRule = { ...rule };
// Bug of `async-validator`
// https://github.com/react-component/field-form/issues/316
// https://github.com/react-component/field-form/issues/313
delete (cloneRule as any).ruleIndex;
// We should special handle array validate
let subRuleField: RuleObject = null;
if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) {
subRuleField = cloneRule.defaultField;
delete cloneRule.defaultField;
}
const validator = new AsyncValidator({
[name]: [cloneRule],
});
const messages = setValues({}, defaultValidateMessages, options.validateMessages);
validator.messages(messages);
let result = [];
try {
await Promise.resolve(validator.validate({ [name]: value }, { ...options }));
} catch (errObj) {
if (errObj.errors) {
result = errObj.errors.map(({ message }, index) =>
// Wrap ReactNode with `key`
React.isValidElement(message)
? React.cloneElement(message, { key: `error_${index}` })
: message,
);
} else {
console.error(errObj);
result = [messages.default];
}
}
if (!result.length && subRuleField) {
const subResults: string[][] = await Promise.all(
(value as StoreValue[]).map((subValue: StoreValue, i: number) =>
validateRule(`${name}.${i}`, subValue, subRuleField, options, messageVariables),
),
);
return subResults.reduce((prev, errors) => [...prev, ...errors], []);
}
// Replace message with variables
const kv = {
...(rule as Record<string, string | number>),
name,
enum: (rule.enum || []).join(', '),
...messageVariables,
};
const fillVariableResult = result.map(error => {
if (typeof error === 'string') {
return replaceMessage(error, kv);
}
return error;
});
return fillVariableResult;
}
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
export function validateRules(
namePath: InternalNamePath,
value: StoreValue,
rules: RuleObject[],
options: ValidateOptions,
validateFirst: boolean | 'parallel',
messageVariables?: Record<string, string>,
) {
const name = namePath.join('.');
// Fill rule with context
const filledRules: RuleObject[] = rules
.map((currentRule, ruleIndex) => {
const originValidatorFunc = currentRule.validator;
const cloneRule = {
...currentRule,
ruleIndex,
};
// Replace validator if needed
if (originValidatorFunc) {
cloneRule.validator = (rule, val, callback) => {
let hasPromise = false;
// Wrap callback only accept when promise not provided
const wrappedCallback = (...args: string[]) => {
// Wait a tick to make sure return type is a promise
Promise.resolve().then(() => {
warning(
!hasPromise,
'Your validator function has already return a promise. `callback` will be ignored.',
);
if (!hasPromise) {
callback(...args);
}
});
};
// Get promise
const promise = originValidatorFunc(rule, val, wrappedCallback);
hasPromise =
promise && typeof promise.then === 'function' && typeof promise.catch === 'function';
/**
* 1. Use promise as the first priority.
* 2. If promise not exist, use callback with warning instead
*/
warning(hasPromise, '`callback` is deprecated. Please return a promise instead.');
if (hasPromise) {
(promise as Promise<void>)
.then(() => {
callback();
})
.catch(err => {
callback(err || ' ');
});
}
};
}
return cloneRule;
})
.sort(({ warningOnly: w1, ruleIndex: i1 }, { warningOnly: w2, ruleIndex: i2 }) => {
if (!!w1 === !!w2) {
// Let keep origin order
return i1 - i2;
}
if (w1) {
return 1;
}
return -1;
});
// Do validate rules
let summaryPromise: Promise<RuleError[]>;
if (validateFirst === true) {
// >>>>> Validate by serialization
summaryPromise = new Promise(async (resolve, reject) => {
/* eslint-disable no-await-in-loop */
for (let i = 0; i < filledRules.length; i += 1) {
const rule = filledRules[i];
const errors = await validateRule(name, value, rule, options, messageVariables);
if (errors.length) {
reject([{ errors, rule }]);
return;
}
}
/* eslint-enable */
resolve([]);
});
} else {
// >>>>> Validate by parallel
const rulePromises: Promise<RuleError>[] = filledRules.map(rule =>
validateRule(name, value, rule, options, messageVariables).then(errors => ({ errors, rule })),
);
summaryPromise = (
validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)
).then((errors: RuleError[]): RuleError[] | Promise<RuleError[]> => {
// Always change to rejection for Field to catch
return Promise.reject<RuleError[]>(errors);
});
}
// Internal catch error to avoid console error log.
summaryPromise.catch(e => e);
return summaryPromise;
}
async function finishOnAllFailed(rulePromises: Promise<RuleError>[]): Promise<RuleError[]> {
return Promise.all(rulePromises).then(
(errorsList: RuleError[]): RuleError[] | Promise<RuleError[]> => {
const errors: RuleError[] = [].concat(...errorsList);
return errors;
},
);
}
async function finishOnFirstFailed(rulePromises: Promise<RuleError>[]): Promise<RuleError[]> {
let count = 0;
return new Promise(resolve => {
rulePromises.forEach(promise => {
promise.then(ruleError => {
if (ruleError.errors.length) {
resolve([ruleError]);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
});
}