validateUtil.js
11.5 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validateRules = validateRules;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _asyncValidator = _interopRequireDefault(require("async-validator"));
var React = _interopRequireWildcard(require("react"));
var _warning = _interopRequireDefault(require("rc-util/lib/warning"));
var _valueUtil = require("./valueUtil");
var _messages = require("./messages");
// Remove incorrect original ts define
var AsyncValidator = _asyncValidator.default;
/**
* Replace with template.
* `I'm ${name}` + { name: 'bamboo' } = I'm bamboo
*/
function replaceMessage(template, kv) {
return template.replace(/\$\{\w+\}/g, function (str) {
var key = str.slice(2, -1);
return kv[key];
});
}
/**
* We use `async-validator` to validate rules. So have to hot replace the message with validator.
* { required: '${name} is required' } => { required: () => 'field is required' }
*/
function convertMessages(messages, name, rule, messageVariables) {
var kv = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, rule), {}, {
name: name,
enum: (rule.enum || []).join(', ')
});
var replaceFunc = function replaceFunc(template, additionalKV) {
return function () {
return replaceMessage(template, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, kv), additionalKV));
};
};
/* eslint-disable no-param-reassign */
function fillTemplate(source) {
var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Object.keys(source).forEach(function (ruleName) {
var value = source[ruleName];
if (typeof value === 'string') {
target[ruleName] = replaceFunc(value, messageVariables);
} else if (value && (0, _typeof2.default)(value) === 'object') {
target[ruleName] = {};
fillTemplate(value, target[ruleName]);
} else {
target[ruleName] = value;
}
});
return target;
}
/* eslint-enable */
return fillTemplate((0, _valueUtil.setValues)({}, _messages.defaultValidateMessages, messages));
}
function validateRule(_x, _x2, _x3, _x4, _x5) {
return _validateRule.apply(this, arguments);
}
/**
* We use `async-validator` to validate the value.
* But only check one value in a time to avoid namePath validate issue.
*/
function _validateRule() {
_validateRule = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(name, value, rule, options, messageVariables) {
var cloneRule, subRuleField, validator, messages, result, subResults;
return _regenerator.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
cloneRule = (0, _objectSpread2.default)({}, rule); // We should special handle array validate
subRuleField = null;
if (cloneRule && cloneRule.type === 'array' && cloneRule.defaultField) {
subRuleField = cloneRule.defaultField;
delete cloneRule.defaultField;
}
validator = new AsyncValidator((0, _defineProperty2.default)({}, name, [cloneRule]));
messages = convertMessages(options.validateMessages, name, cloneRule, messageVariables);
validator.messages(messages);
result = [];
_context2.prev = 7;
_context2.next = 10;
return Promise.resolve(validator.validate((0, _defineProperty2.default)({}, name, value), (0, _objectSpread2.default)({}, options)));
case 10:
_context2.next = 15;
break;
case 12:
_context2.prev = 12;
_context2.t0 = _context2["catch"](7);
if (_context2.t0.errors) {
result = _context2.t0.errors.map(function (_ref2, index) {
var message = _ref2.message;
return (// Wrap ReactNode with `key`
/*#__PURE__*/
React.isValidElement(message) ? /*#__PURE__*/React.cloneElement(message, {
key: "error_".concat(index)
}) : message
);
});
} else {
console.error(_context2.t0);
result = [messages.default()];
}
case 15:
if (!(!result.length && subRuleField)) {
_context2.next = 20;
break;
}
_context2.next = 18;
return Promise.all(value.map(function (subValue, i) {
return validateRule("".concat(name, ".").concat(i), subValue, subRuleField, options, messageVariables);
}));
case 18:
subResults = _context2.sent;
return _context2.abrupt("return", subResults.reduce(function (prev, errors) {
return [].concat((0, _toConsumableArray2.default)(prev), (0, _toConsumableArray2.default)(errors));
}, []));
case 20:
return _context2.abrupt("return", result);
case 21:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[7, 12]]);
}));
return _validateRule.apply(this, arguments);
}
function validateRules(namePath, value, rules, options, validateFirst, messageVariables) {
var name = namePath.join('.'); // Fill rule with context
var filledRules = rules.map(function (currentRule) {
var originValidatorFunc = currentRule.validator;
if (!originValidatorFunc) {
return currentRule;
}
return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, currentRule), {}, {
validator: function validator(rule, val, callback) {
var hasPromise = false; // Wrap callback only accept when promise not provided
var wrappedCallback = function wrappedCallback() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Wait a tick to make sure return type is a promise
Promise.resolve().then(function () {
(0, _warning.default)(!hasPromise, 'Your validator function has already return a promise. `callback` will be ignored.');
if (!hasPromise) {
callback.apply(void 0, args);
}
});
}; // Get promise
var 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
*/
(0, _warning.default)(hasPromise, '`callback` is deprecated. Please return a promise instead.');
if (hasPromise) {
promise.then(function () {
callback();
}).catch(function (err) {
callback(err || ' ');
});
}
}
});
});
var summaryPromise;
if (validateFirst === true) {
// >>>>> Validate by serialization
summaryPromise = new Promise( /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(resolve, reject) {
var i, errors;
return _regenerator.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
i = 0;
case 1:
if (!(i < filledRules.length)) {
_context.next = 11;
break;
}
_context.next = 4;
return validateRule(name, value, filledRules[i], options, messageVariables);
case 4:
errors = _context.sent;
if (!errors.length) {
_context.next = 8;
break;
}
reject(errors);
return _context.abrupt("return");
case 8:
i += 1;
_context.next = 1;
break;
case 11:
/* eslint-enable */
resolve([]);
case 12:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x6, _x7) {
return _ref.apply(this, arguments);
};
}());
} else {
// >>>>> Validate by parallel
var rulePromises = filledRules.map(function (rule) {
return validateRule(name, value, rule, options, messageVariables);
});
summaryPromise = (validateFirst ? finishOnFirstFailed(rulePromises) : finishOnAllFailed(rulePromises)).then(function (errors) {
if (!errors.length) {
return [];
}
return Promise.reject(errors);
});
} // Internal catch error to avoid console error log.
summaryPromise.catch(function (e) {
return e;
});
return summaryPromise;
}
function finishOnAllFailed(_x8) {
return _finishOnAllFailed.apply(this, arguments);
}
function _finishOnAllFailed() {
_finishOnAllFailed = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3(rulePromises) {
return _regenerator.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", Promise.all(rulePromises).then(function (errorsList) {
var _ref3;
var errors = (_ref3 = []).concat.apply(_ref3, (0, _toConsumableArray2.default)(errorsList));
return errors;
}));
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _finishOnAllFailed.apply(this, arguments);
}
function finishOnFirstFailed(_x9) {
return _finishOnFirstFailed.apply(this, arguments);
}
function _finishOnFirstFailed() {
_finishOnFirstFailed = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee4(rulePromises) {
var count;
return _regenerator.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
count = 0;
return _context4.abrupt("return", new Promise(function (resolve) {
rulePromises.forEach(function (promise) {
promise.then(function (errors) {
if (errors.length) {
resolve(errors);
}
count += 1;
if (count === rulePromises.length) {
resolve([]);
}
});
});
}));
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return _finishOnFirstFailed.apply(this, arguments);
}