Can we get a best practice guide on setting up routes in terms of having resources in individual .js files?
Should we just require all resources into the main server.js. What is recommended?
Generally speaking, many prefer to separate the route handler functions into their own root /handlers directory, with an additional /handlers/universal directory for commonly shared handlers. Having handlers in their own files encourages trying to keep them separate and distinct without bleeding out too much state. The server file exports just the setup of the server object itself.
Depending on how complex your project is, you can then have another file (either your main.js or some file that's doing startup tasks) take that server object and install the routes into it. Or you can keep it in server.js if it's fairly readable. When your set of _n_ startup tasks are complete, you can finally call listen on the server to start taking traffic. These are not hard and fast rules, of course.
A best practices/guide is something we'd love to have - just unfortunately not enough time to get to it!
@DonutEspresso can you give an example using the hello world server and breaking up into three files server.js, handlers/Users.js, handlers/Apps.js. Should we just require the two files handlers/Users.js and handlers/Apps.js?
server.js
var restify = require('restify');
var server = restify.createServer({
name: 'myapp',
version: '1.0.0'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
// this this right?
require('handlers/Users.js')(server);
require('handlers/Apps.js')(server);
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
handlers/Users.js
function Users(server) {
server.get('/users', function (req, res, next) {
res.send(req.params);
return next();
});
};
module.exports = Users;
handlers/Apps.js
function Apps(server) {
server.get('/apps', function (req, res, next) {
res.send(req.params);
return next();
});
};
module.exports = Apps;
That looks like it will work, you could also combine the logic in server.js a bit:
//require and init
function requireAndInit(handlers) {
handlers.map((handler) => {
require(handler).call(null, server);
});
}
requireAndInit([
'handlers/Users',
'handlers/Apps'
// Assuming this list gets long
]);
You could take it a step further and pass in the directory where your handlers are stored, then walk the tree using something like walkdir but that wouldn't guarantee order of precedence when registering.
See my simple and clean example for breaking out routes here. Route files are added to the route directory and combined in index.js.
Most helpful comment
See my simple and clean example for breaking out routes here. Route files are added to the route directory and combined in index.js.