Last active
August 29, 2015 14:10
-
-
Save gwithian/a765c8091fd37228e4a4 to your computer and use it in GitHub Desktop.
creates swagger-node-express/swagger-node-restify resource action to return objects from a dataset which match the values of path params
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
/** | |
* creates a swagger-node-restify action which returns an array of filtered data items based on request params | |
* @param {array} data a flat array of objects to query | |
* @param {object[]} filters object or array of objects describing a mapping between a request param and a property of the data | |
* @param {string} filters[].prop property of data object to match | |
* @param {string} filters[].param name of request param containing value to match | |
* @param {boolean, optional} singleResult `true` to return the first match as an object instead of array of results | |
* @return {function} request handler to use as `action` in swagger-node-restify resource description | |
*/ | |
var createQueryAction = function (data, filters, singleResult) { | |
var hasValueForProp = function (prop, val, obj) { | |
return Object.prototype.hasOwnProperty.call(obj, prop) && (obj[prop] === val); | |
}; | |
var objectFilter = function (prop, val) { | |
return hasValueForProp.bind(null, prop, val); | |
}; | |
//wrap in array if single filter | |
if (!(filters instanceof Array)) filters = [filters]; | |
//return request handler | |
return function queryAction(req, res) { | |
var matches = data; | |
//run each filter in series on the dataset | |
filters.forEach(function (filter) { | |
//filter the data using the query param | |
matches = matches.filter(objectFilter(filter.prop, req.params[filter.param])); | |
//if we've ended up with no matches then bail out... | |
if (!matches.length) throw swagger.errors.notFound(filter.param); | |
}); | |
//returns single match if singleResult == true | |
res.send( singleResult ? matches[0] : matches ); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example
Create an action for a swagger resource that gets a single item from an array of data matching an 'itemId' path param: