UNPKG

2.32 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/builtin/interopRequireDefault");
4
5exports.__esModule = true;
6exports.default = void 0;
7
8var _has = _interopRequireDefault(require("lodash/has"));
9
10var _isSchema = _interopRequireDefault(require("./util/isSchema"));
11
12function callOrConcat(schema) {
13 if (typeof schema === 'function') return schema;
14 return function (base) {
15 return base.concat(schema);
16 };
17}
18
19var Conditional =
20/*#__PURE__*/
21function () {
22 function Conditional(refs, options) {
23 var is = options.is,
24 then = options.then,
25 otherwise = options.otherwise;
26 this.refs = [].concat(refs);
27 then = callOrConcat(then);
28 otherwise = callOrConcat(otherwise);
29 if (typeof options === 'function') this.fn = options;else {
30 if (!(0, _has.default)(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');
31 if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
32 var isFn = typeof is === 'function' ? is : function () {
33 for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
34 values[_key] = arguments[_key];
35 }
36
37 return values.every(function (value) {
38 return value === is;
39 });
40 };
41
42 this.fn = function () {
43 for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
44 values[_key2] = arguments[_key2];
45 }
46
47 var currentSchema = values.pop();
48 var option = isFn.apply(void 0, values) ? then : otherwise;
49 return option(currentSchema);
50 };
51 }
52 }
53
54 var _proto = Conditional.prototype;
55
56 _proto.getValue = function getValue(parent, context) {
57 var values = this.refs.map(function (r) {
58 return r.getValue(parent, context);
59 });
60 return values;
61 };
62
63 _proto.resolve = function resolve(ctx, values) {
64 var schema = this.fn.apply(ctx, values.concat(ctx));
65 if (schema !== undefined && !(0, _isSchema.default)(schema)) throw new TypeError('conditions must return a schema object');
66 return schema || ctx;
67 };
68
69 return Conditional;
70}();
71
72var _default = Conditional;
73exports.default = _default;
74module.exports = exports["default"];
\No newline at end of file