Last active
June 21, 2017 10:27
-
-
Save mrhammadasif/04b016081bde6849ae4b97df2b3d8c12 to your computer and use it in GitHub Desktop.
Load Dynamic Routes Recursively in ExpressJS App
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
// A file in `routes/` folder | |
module.exports = (function(app, router){ | |
router | |
.route('/books') | |
.get((req, res, next)=>{ | |
if(err){ | |
next(err); | |
// send it to error handler | |
} | |
else{ | |
res.json({"books": ["book1", "book2", "bookn"]}); | |
} | |
}); | |
router | |
.route('book/:id') | |
.get((req, res, next) => { /* Custom Functionality for getting specific book */}) | |
.put((req, res, next) => { /* Custom Functionality for updateing specific book record in DB */}); | |
})(app, router); |
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
// routes | |
processRoutePath(__dirname + "/routes"); | |
function processRoutePath(route_path) { | |
fs.readdirSync(route_path).forEach(function(file) { | |
var filepath = route_path + '/' + file; | |
fs.stat(filepath, function(err,stat) { | |
if (stat.isDirectory()) { | |
processRoutePath(filepath); | |
} else { | |
let router = express.Router(); | |
console.info('Loading route: ' + filepath); | |
require(filepath)(app, router); | |
app.use("/" + filepath, router); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment