@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
72 lines (71 loc) • 2.42 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = normalizeFieldValue;
exports.normalizeValueToArray = normalizeValueToArray;
const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
function normalizeFieldValue(schemaId, schemaName, schemasById, field, value, options) {
let localValue = normalizeValueToArray(value);
if (!Array.isArray(localValue)) {
throw new SpruceError_1.default({
code: 'INVALID_PARAMETERS',
parameters: [field.name],
friendlyMessages: [`I was expecting an array for ${field.name}.`],
});
}
const { shouldCreateEntityInstances: createEntityInstances = true, ...extraOptions } = options ?? {};
const validate = extraOptions.shouldValidate ?? true;
const baseOptions = {
schemasById,
...(field.definition.options ?? {}),
...extraOptions,
};
if (value === null || typeof value === 'undefined') {
if (field && (!validate || !field.isRequired)) {
return value;
}
else {
throw new SpruceError_1.default({
code: !field ? 'UNEXPECTED_PARAMETERS' : 'MISSING_PARAMETERS',
parameters: [field.name],
});
}
}
let errors = [];
if (validate) {
localValue.forEach((value) => {
errors = [
...errors,
...field.validate(value, {
...baseOptions,
}),
];
});
}
if (errors.length > 0) {
throw new SpruceError_1.default({
code: 'VALIDATION_FAILED',
schemaId,
errors,
schemaName,
});
}
if (localValue.length > 0) {
localValue = localValue.map((value) => typeof value === 'undefined' || value === null
? value
: field.toValueType(value, {
createEntityInstances,
...baseOptions,
}));
}
return (field.isArray ? localValue : localValue[0]);
}
function normalizeValueToArray(value) {
return value === null || typeof value === 'undefined'
? []
: Array.isArray(value)
? value
: [value];
}