@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
39 lines (38 loc) • 1.77 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = normalizeSchemaValues;
const just_safe_get_1 = __importDefault(require("just-safe-get"));
const SchemaEntityFactory_1 = __importDefault(require("../factories/SchemaEntityFactory"));
const expandValues_1 = __importDefault(require("./expandValues"));
function normalizeSchemaValues(schema, values, options) {
const instance = SchemaEntityFactory_1.default.Entity(schema, (0, expandValues_1.default)(values));
const { shouldCreateEntityInstances = false, fields, shouldRetainDotNotationKeys, ...rest } = options || {};
let areAnyKeysDotted = false;
const normalizedFields = fields?.map((f) => {
const hasDotKey = f.includes('.');
areAnyKeysDotted = areAnyKeysDotted || hasDotKey;
return hasDotKey ? f.split('.')[0] : f;
});
const normalizedOptions = {
shouldCreateEntityInstances,
fields: normalizedFields,
...rest,
};
let normalized = instance.getValues(normalizedOptions);
const shouldConvertToDotNotation = areAnyKeysDotted || shouldRetainDotNotationKeys;
if (shouldRetainDotNotationKeys || shouldConvertToDotNotation) {
const normalizedWithKeys = {};
const keys = fields || Object.keys(values);
for (const key of keys) {
normalizedWithKeys[key] = (0, just_safe_get_1.default)(normalized, key);
}
normalized = normalizedWithKeys;
}
if (!shouldRetainDotNotationKeys && shouldConvertToDotNotation) {
normalized = (0, expandValues_1.default)(normalized);
}
return normalized;
}