@indec/form-builder
Version:
Form builder
220 lines (219 loc) • 10.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = buildYupSchema;
var Yup = _interopRequireWildcard(require("yup"));
var _dateTypes = _interopRequireDefault(require("../constants/dateTypes"));
var _questionTypes = _interopRequireDefault(require("../constants/questionTypes"));
var _getValidationRules = _interopRequireDefault(require("./getValidationRules"));
var _getNavigation = _interopRequireDefault(require("./getNavigation"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var getValidatorType = function getValidatorType(type, options, metadata) {
switch (type) {
case _questionTypes["default"].TEXT_FIELD:
case _questionTypes["default"].DROPDOWN:
case _questionTypes["default"].RADIO:
return Yup.string()["default"]('');
case _questionTypes["default"].CURRENCY:
case _questionTypes["default"].NUMERIC_FIELD:
return Yup.number().transform(function (value) {
return Number.isNaN(value) || value === null || value === '' ? undefined : value;
});
case _questionTypes["default"].CHECKBOX:
return Yup.array().of(Yup.string());
case _questionTypes["default"].RADIO_TABLE:
{
var opts = options.reduce(function (accumulator, currentValue) {
return _objectSpread(_objectSpread({}, accumulator), {}, _defineProperty({}, currentValue.name, Yup.string()["default"]('')));
}, {});
return Yup.object(opts);
}
case _questionTypes["default"].DATE:
{
var field = Yup.string()["default"]('');
if ([_dateTypes["default"].RANGE_WITHOUT_HOUR, _dateTypes["default"].RANGE_WITH_HOUR].includes(metadata.dateType)) {
return Yup.object({
start: field,
end: field
});
}
return Yup.string();
}
default:
return null;
}
};
var ValidatorSchema = /*#__PURE__*/function () {
function ValidatorSchema(props) {
_classCallCheck(this, ValidatorSchema);
Object.assign(this, props);
}
return _createClass(ValidatorSchema, [{
key: "handleValidations",
value: function handleValidations(_ref) {
var _this = this;
var validator = _ref.validator,
validations = _ref.validations,
answers = _ref.answers,
questionName = _ref.questionName;
var name = this.question.name;
var initialValues = this.initialValues,
section = this.section,
sections = this.sections;
var newValidator = validator;
validations.forEach(function (validation) {
var messageType = validation.message.type;
if (messageType === 'warning' && _this.opts.schemaType !== 'warning' || messageType === 'error' && _this.opts.schemaType !== 'error') {
return;
}
newValidator = newValidator.test('custom-validation', validation.message.text, function customValidation(currentValue) {
var formatAnswer = answers;
formatAnswer = _objectSpread(_objectSpread({}, formatAnswer), {}, _defineProperty({}, questionName, {
answer: {
value: currentValue
}
}));
var rules = (0, _getValidationRules["default"])({
validation: validation,
answers: formatAnswer,
initialValues: initialValues,
section: section,
sections: sections,
questionName: name
});
if (rules.some(function (value) {
return value === true;
})) {
return this.createError({
path: this.path,
message: validation.message.text
});
}
return true;
});
});
return newValidator;
}
}, {
key: "buildSubQuestionsValidations",
value: function buildSubQuestionsValidations(subQuestions, answers) {
var _this2 = this;
return subQuestions.reduce(function (acc, currentValue) {
var subQuestionValidator = getValidatorType(currentValue.type, currentValue.options);
acc[currentValue.name] = Yup.object({
answer: Yup.object({
value: Yup.lazy(function (value) {
return _this2.handleValidations({
validator: subQuestionValidator,
validations: currentValue.validations,
answers: _objectSpread(_objectSpread({}, _this2.answers), {}, _defineProperty({}, _this2.question.name, {
answer: _objectSpread(_objectSpread({}, answers[_this2.question.name].answer), {}, {
specifications: _objectSpread(_objectSpread({}, answers[_this2.question.name].answer.specifications), {}, _defineProperty({}, currentValue.name, {
answer: {
value: value
}
}))
})
})),
questionName: currentValue.name
});
})
})
});
return acc;
}, {});
}
}, {
key: "getSelectedSubQuestions",
value: function getSelectedSubQuestions(_ref2) {
var _this3 = this;
var value = _ref2.value;
return this.question.subQuestions.filter(function (subQuestion) {
var navigation = (0, _getNavigation["default"])({
navigation: subQuestion.navigation,
answers: _defineProperty({}, _this3.question.name, {
answer: value
}),
section: _this3.section,
initialValues: _this3.initialValues,
sections: _this3.sections
});
return navigation.valid;
});
}
}, {
key: "getSubQuestionsSchema",
value: function getSubQuestionsSchema(schema, value) {
var newSchema = schema;
var subQuestionsToRender = this.getSelectedSubQuestions({
value: value
});
newSchema = schema.concat(Yup.object({
specifications: Yup.object(this.buildSubQuestionsValidations(subQuestionsToRender, _defineProperty({}, this.question.name, {
answer: value
})))
}));
return newSchema;
}
}, {
key: "buildAnswerObj",
value: function buildAnswerObj(_ref3) {
var _this4 = this;
var validator = _ref3.validator;
var schema = Yup.object({
value: validator
});
if (this.question.multiple) {
return Yup.array().of(Yup.lazy(function (value) {
return _this4.question.subQuestions.length > 0 ? _this4.getSubQuestionsSchema(schema, value) : schema;
}));
}
return this.question.subQuestions.length > 0 ? this.getSubQuestionsSchema(schema, this.answers[this.question.name].answer) : schema;
}
}]);
}();
function buildYupSchema(schema, question, sections, section, initialValues, values) {
var opts = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {};
var schemaWithValidations = schema;
var name = question.name,
type = question.type,
options = question.options,
metadata = question.metadata;
var validator = getValidatorType(type, options, metadata);
if (!validator) {
return schemaWithValidations;
}
var validationSchema = new ValidatorSchema({
answers: values,
question: question,
opts: opts,
initialValues: initialValues,
section: section,
sections: sections
});
validator = validationSchema.handleValidations({
validator: validator,
validations: question.validations,
answers: values,
questionName: name
});
schemaWithValidations[name] = Yup.object({
id: Yup.number().required(),
answer: validationSchema.buildAnswerObj({
validator: validator
})
});
return schemaWithValidations;
}