Last active
May 18, 2016 23:26
-
-
Save jaredallard/7dc3b11e93526b7136789e5e3d6cad6c to your computer and use it in GitHub Desktop.
Dynamically Create Express Routes.
This file contains hidden or 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
'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