@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
66 lines (65 loc) • 2.21 kB
JavaScript
import SpruceError from '../errors/SpruceError.js';
export default function normalizeFieldValue(schemaId, schemaName, schemasById, field, value, options) {
var _a, _b;
let localValue = normalizeValueToArray(value);
if (!Array.isArray(localValue)) {
throw new SpruceError({
code: 'INVALID_PARAMETERS',
parameters: [field.name],
friendlyMessages: [`I was expecting an array for ${field.name}.`],
});
}
const { shouldCreateEntityInstances: createEntityInstances = true, ...extraOptions } = options !== null && options !== void 0 ? options : {};
const validate = (_a = extraOptions.shouldValidate) !== null && _a !== void 0 ? _a : true;
const baseOptions = {
schemasById,
...((_b = field.definition.options) !== null && _b !== void 0 ? _b : {}),
...extraOptions,
};
if (value === null || typeof value === 'undefined') {
if (field && (!validate || !field.isRequired)) {
return value;
}
else {
throw new SpruceError({
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({
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]);
}
export function normalizeValueToArray(value) {
return value === null || typeof value === 'undefined'
? []
: Array.isArray(value)
? value
: [value];
}