vtils
Version:
一个面向业务的 JavaScript/TypeScript 实用程序库。
47 lines • 2.02 kB
JavaScript
import { has } from "../../utils/index.js";
import isSchema from "./util/isSchema.js";
var Condition = /*#__PURE__*/function () {
function Condition(refs, options) {
this.refs = refs;
if (typeof options === 'function') {
this.fn = options;
return;
}
if (!has(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');
if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
var is = options.is,
then = options.then,
otherwise = options.otherwise;
var check = typeof is === 'function' ? is : function () {
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
values[_key] = arguments[_key];
}
return values.every(function (value) {
return value === is;
});
};
this.fn = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var options = args.pop();
var schema = args.pop();
var branch = check.apply(void 0, args) ? then : otherwise;
if (!branch) return undefined;
if (typeof branch === 'function') return branch(schema);
return schema.concat(branch.resolve(options));
};
}
var _proto = Condition.prototype;
_proto.resolve = function resolve(base, options) {
var values = this.refs.map(function (ref) {
return ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context, options == null ? void 0 : options.rootValue);
});
var schema = this.fn.apply(base, values.concat(base, options));
if (schema === undefined || schema === base) return base;
if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
return schema.resolve(options);
};
return Condition;
}();
export default Condition;