You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.8 KiB
JavaScript

'use strict';
const dotty = require("dotty");
const deepAssign = require("deep-assign");
module.exports = function createPropertyMapper(propertyMap) {
let mappings = Object.keys(propertyMap).map((sourceProperty) => {
let destinationPath = propertyMap[sourceProperty];
if (typeof destinationPath === "function") {
return {
sourceProperty: sourceProperty,
transformer: destinationPath
}
} else {
let destinationPathParts = destinationPath.split(".");
let destinationObject = destinationPathParts[0];
let destinationProperty = destinationPathParts.slice(1).join(".");
return {
sourceProperty: sourceProperty,
destinationObject: destinationObject,
destinationProperty: destinationProperty
}
}
});
return function mapProperties(properties) {
return mappings.map((mapping) => {
if (properties[mapping.sourceProperty] != null) {
return Object.assign({
value: properties[mapping.sourceProperty]
}, mapping);
}
}).filter((item) => {
return (item != null);
}).reduce((objects, item) => {
function ensureObject(object) {
if (objects[object] == null) {
objects[object] = {};
}
}
if (item.destinationProperty != null) {
ensureObject(item.destinationObject);
dotty.put(objects[item.destinationObject], item.destinationProperty, item.value);
} else {
let results = item.transformer(item.value);
Object.keys(results).forEach((object) => {
ensureObject(object);
deepAssign(objects[object], results[object]);
});
}
return objects;
}, {})
}
};
let mapper = module.exports({
foo: "one.foo",
bar: "two.bar",
twoFoo: "two.foo",
baz: (value) => {
return {
one: {
baz: value
},
two: {
baz: value
}
}
}
});
console.log(mapper({
foo: "hello one foo!",
bar: "hello bar!",
twoFoo: "hello two foo!",
baz: "hello baz!"
}));