Skip to content

Instantly share code, notes, and snippets.

@gwithian
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwithian/a765c8091fd37228e4a4 to your computer and use it in GitHub Desktop.
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
/**
* 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 );
};
};
@gwithian
Copy link
Author

Usage example
Create an action for a swagger resource that gets a single item from an array of data matching an 'itemId' path param:

  var items = [
    {
      'id': 'item1',
      'name': 'foo'
    },
    {
      'id': 'item2',
      'name': 'bar'
    },
    {...}
  ];


  exports.getItemById = {

    'spec': {
      "path" : "/items/{itemId}",
      "notes" : "Returns a single item",
      "summary" : "Get item by id",
      "method": "GET",
      "parameters" : [swagger.pathParam("itemId", "id of an item to fetch", "string")],
      "type" : "Item",
      "responseMessages" : [swagger.errors.notFound('Item')],
      "nickname": "getItemById"
    },

    //third arg `true` creates a function which returns a single matching object rather than an array
    'action': createQueryAction(items, { prop: 'id', param: 'itemId' }, true)

  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment