Skip to content

Instantly share code, notes, and snippets.

@fluffywaffles
Created March 10, 2015 01:19
Show Gist options
  • Save fluffywaffles/9ed377a15ef75b2a6856 to your computer and use it in GitHub Desktop.
Save fluffywaffles/9ed377a15ef75b2a6856 to your computer and use it in GitHub Desktop.
The Superroute!
var router = express.Router()
, Response = require('../models/response.js');
// NOTE(jordan): LET'S BUILD TEH SUPERROUTE
router.get('/:program/:pfilter?/:endpoint/:efilter?/:action?', function(req, res) {
// NOTE(jordan): so many optional parameters!!!
var program = req.params.program
, pfilter = req.params.pfilter
, endpoint = req.params.endpoint
, efilter = req.params.efilter
, action = req.params.action
, query;
var send = function(err, data) {
if(err) console.log(err) && res.send(500, 'Whoa, popped a gasket. Whoops.');
if (data == '' || data == [])
res.send([]);
else res.send(isNaN(data) ? data : data.toString());
}
// NOTE(jordan): all queries should be 'startsWith' and case insensitive
var rxsi = function (val) { return new RegExp('^' + val, 'i'); }
if (pfilter && pfilter.indexOf(':') < 0)
action = efilter, efilter = endpoint, endpoint = pfilter, pfilter = undefined;
if (efilter && efilter.indexOf(':') < 0)
action = efilter, efilter = undefined;
if(endpoint = 'applications') {
query = Response.find({});
}
// TODO(jordan): same for pfilter...
efilter && efilter.split(',').forEach(function(filterArg) {
filterArg = filterArg.split(':');
if (filterArg[0].charAt(0) == '~')
query = filterArg.length == 2
? query[filterArg[0].slice(1)](filterArg[1])
: query;
else query = filterArg.length == 2
? query.where(filterArg[0]).equals(rxsi(filterArg[1]))
: query.where(filterArg[0])[filterArg[1]](rxsi(filterArg[2]));
})
if (action == 'count') {
query.count(send);
} else {
query.exec(send);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment