UNPKG

@sprucelabs/schema

Version:

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

73 lines (72 loc) • 2.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const SpruceError_1 = __importDefault(require("../errors/SpruceError")); class KeyMapper { constructor(map) { this.map = map; } mapTo(values, options) { return this._mapTo(values, this.map, options?.shouldThrowOnUnmapped ?? true); } mapFrom(values, options) { return this._mapFrom(values, this.map, options?.shouldThrowOnUnmapped ?? true); } mapFieldNameTo(name) { if (!this.map[name]) { this.throwFieldsNotMapped([name]); } return this.map[name]; } throwFieldsNotMapped(fields) { throw new SpruceError_1.default({ code: 'FIELDS_NOT_MAPPED', fields, }); } mapFieldNameFrom(name) { for (const key in this.map) { if (this.map.hasOwnProperty(key)) { if (this.map[key] === name) { return key; } } } this.throwFieldsNotMapped([name]); return 'never hit'; } _mapTo(values, map, shouldThrowOnUnmapped = true) { const foundFields = []; let target = {}; for (const key in map) { if (values.hasOwnProperty(key)) { target[map[key]] = values[key]; foundFields.push(key); } } const missingFields = Object.keys(values).filter((key) => !foundFields.includes(key)); if (shouldThrowOnUnmapped && missingFields.length > 0) { this.throwFieldsNotMapped(missingFields); } return target; } _mapFrom(values, map, shouldThrowOnUnmapped = true) { const foundFields = []; let target = {}; for (const targetKey in map) { const sourceKey = map[targetKey]; if (values.hasOwnProperty(sourceKey)) { target[targetKey] = values[sourceKey]; foundFields.push(sourceKey); } } const missingFields = Object.keys(values).filter((key) => !foundFields.includes(key)); if (shouldThrowOnUnmapped && missingFields.length > 0) { this.throwFieldsNotMapped(missingFields); } return target; } } exports.default = KeyMapper;