UNPKG

@sprucelabs/schema

Version:

Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓

33 lines (32 loc) • 1.43 kB
import get from 'just-safe-get'; import EntityFactory from '../factories/SchemaEntityFactory.js'; import expandValues from './expandValues.js'; export default function normalizeSchemaValues(schema, values, options) { const instance = EntityFactory.Entity(schema, expandValues(values)); const { shouldCreateEntityInstances = false, fields, shouldRetainDotNotationKeys, ...rest } = options || {}; let areAnyKeysDotted = false; const normalizedFields = fields === null || fields === void 0 ? void 0 : 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] = get(normalized, key); } normalized = normalizedWithKeys; } if (!shouldRetainDotNotationKeys && shouldConvertToDotNotation) { normalized = expandValues(normalized); } return normalized; }