UNPKG

@commodo/fields

Version:

Enables defining rich data models by decorating function instances with specified model fields. Additionally, it adds `populate` and `validate` methods, for populating model instances with data, and then validating it, respectively.

75 lines (63 loc) 1.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _repropose = require("repropose"); var _fields = require("@commodo/fields"); const throwDataTypeError = (fieldType, fieldName, value) => { throw new _fields.WithFieldsError(`Invalid data type: ${fieldType} field "${fieldName}" cannot accept value ${value}.`, _fields.WithFieldsError.FIELD_DATA_TYPE_ERROR); }; const validateValue = ({ value, validate, name, type }) => { if (value !== undefined && value !== null) { if (!validate(value, void 0)) { throwDataTypeError(type, name, value); } } }; const withFieldDataTypeValidation = validate => { return (0, _repropose.withProps)(props => { const { setValue } = props; return { setValue(value, ...args) { if (value === null) { return setValue.call(this, value, ...args); } const { list, type, name } = this; if (list) { if (!Array.isArray(value)) { throwDataTypeError(`${type} (list)`, name, `${value} (non-list)`); } value.forEach(item => validateValue({ value: item, validate, name, type })); } else { validateValue({ value, validate, name, type }); } return setValue.call(this, value, ...args); } }; }); }; var _default = withFieldDataTypeValidation; exports.default = _default; //# sourceMappingURL=withFieldDataTypeValidation.js.map