@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
69 lines (68 loc) • 2.38 kB
JavaScript
import SpruceError from '../errors/SpruceError.js';
export default class KeyMapper {
constructor(map) {
this.map = map;
}
mapTo(values, options) {
var _a;
return this._mapTo(values, this.map, (_a = options === null || options === void 0 ? void 0 : options.shouldThrowOnUnmapped) !== null && _a !== void 0 ? _a : true);
}
mapFrom(values, options) {
var _a;
return this._mapFrom(values, this.map, (_a = options === null || options === void 0 ? void 0 : options.shouldThrowOnUnmapped) !== null && _a !== void 0 ? _a : true);
}
mapFieldNameTo(name) {
if (!this.map[name]) {
this.throwFieldsNotMapped([name]);
}
return this.map[name];
}
throwFieldsNotMapped(fields) {
throw new SpruceError({
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;
}
}