Skip to content

Instantly share code, notes, and snippets.

@jaredallard
Last active May 18, 2016 23:26
Show Gist options
  • Save jaredallard/7dc3b11e93526b7136789e5e3d6cad6c to your computer and use it in GitHub Desktop.
Save jaredallard/7dc3b11e93526b7136789e5e3d6cad6c to your computer and use it in GitHub Desktop.
Dynamically Create Express Routes.
'use strict';
const express = require('express');
const async = require('async');
let ROUTES = path.join(__dirname, 'routes', API_VERSION);
fs.readdir(ROUTES, (err, list) => {
if(err) return next();
async.each(list, function(route, next) {
let Path = path.join(ROUTES, route);
let name = path.parse(route).name;
let mount = path.join('/v1/', name)
console.log('mount route', name, 'on', mount);
let eroute;
try {
eroute = require(Path);
} catch(e) {
return next(e);
}
// execute eroute "constructor"
let router = eroute(new express.Router(), dbctl);
// Hook in the newly created route.
app.use(mount, router);
return next()
}, err => {
if(err) return next(err);
return next();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment