@appbuckets/react-ui-smart-components
Version:
UI Extended Components that work with @appbuckets/react-client and @appbuckets/react-ui
96 lines (90 loc) • 2.72 kB
JavaScript
;
var Yup = require('yup');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(
n,
k,
d.get
? d
: {
enumerable: true,
get: function () {
return e[k];
},
}
);
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var Yup__namespace = /*#__PURE__*/ _interopNamespace(Yup);
/* --------
* Main Function
* -------- */
function defaultValuesFromYupSchema(yupSchema) {
/** Assert schema is a valid object schema */
if (!(yupSchema instanceof Yup__namespace.ObjectSchema)) {
throw new Error(
'[ @appbuckets/react-ui-smart-components ] : invalid Yup object schema.'
);
}
/** Check if Scheme has already a default value */
if (yupSchema.spec.default) {
return yupSchema.spec.default;
}
/** Init the result object */
var result = {};
/** Loop fields */
Object.keys(yupSchema.fields).forEach(function (fieldName) {
/** Get the Field */
var field = yupSchema.fields[fieldName];
/** If field is an instance of ObjectSchema, recurse */
if (field instanceof Yup__namespace.ObjectSchema) {
result[fieldName] = defaultValuesFromYupSchema(field);
return;
}
/** Get the default value from field spec */
var defaultValue = field.spec.default;
/** Set the right default based on field type */
switch (field.type) {
case 'boolean':
result[fieldName] = !!defaultValue;
break;
case 'array':
result[fieldName] = Array.isArray(defaultValue) ? defaultValue : [];
break;
case 'number':
result[fieldName] =
typeof defaultValue === 'number' ? defaultValue : '';
break;
case 'date':
result[fieldName] = defaultValue instanceof Date ? defaultValue : '';
break;
case 'string':
result[fieldName] =
typeof defaultValue === 'string' ? defaultValue : '';
break;
default:
if (process.env.NODE_ENV === 'development') {
global.console.warn(
'[ @appbuckets/react-ui-smart-components ] : transforming yup schema to object warning: ' +
'could not find an init default value for type '.concat(
field.type,
'.'
)
);
}
result[fieldName] = defaultValue || '';
}
});
return result;
}
module.exports = defaultValuesFromYupSchema;