Last active
April 13, 2017 20:03
-
-
Save nicklozon/0ac061b236b655f38d02f5f5bc555bee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('lodash'); | |
/** | |
* Takes two objects and a callback. One schema object that contains nested | |
* objects and functions, the other a paramater object with no constraints. The | |
* schema object is traversed recursively and functions are evaluated in place | |
* using the parameter object as the only parameter. The final evaluated object | |
* is passed to the callback. | |
* @param {Object} obj | |
* @param {Object} params | |
* @param {requestCallback} cb | |
*/ | |
function mapSchema(obj, params, cb) { | |
var mapValues; | |
// Recursive functon to evaluate function objects | |
// Omits any values of undefined or null | |
mapValues = function(obj, params) { | |
return _ | |
.chain(obj) | |
.mapValues(function(val) { | |
if(typeof(val) === 'function') { | |
return val(params); | |
} else if(typeof(val) === 'object') { | |
return mapValues(val, params); | |
} else { | |
return val; | |
} | |
}) | |
.omitBy(_.isUndefined) | |
.omitBy(_.isNull) | |
.value(); | |
}; | |
try { | |
cb(mapValues(obj, params)); | |
} catch (ex) { | |
cb(ex); | |
} | |
} | |
module.exports = mapSchema; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment