Implement initial version of composite property mapper

master
Sven Slootweg 7 years ago
parent 0049bb9a53
commit 68da848e76

@ -20,7 +20,9 @@
"license": "WTFPL",
"dependencies": {
"checkit": "^0.7.0",
"default-value": "^1.0.0"
"deep-assign": "^2.0.0",
"default-value": "^1.0.0",
"dotty": "0.0.2"
},
"devDependencies": {
"@joepie91/gulp-preset-es2015": "^1.0.1",

@ -0,0 +1,82 @@
'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!"
}));
Loading…
Cancel
Save