const express = require("express");
const traverse = require("traverse");
// Route building function:
// Expects an initial path used as the root of the route,
// as well as the path the the module within the routes folder
// Routes are build as
// domain.tld[path]/[moduleName]/[modulePath]
// where path is the passed in string, moduleName is one of the strings in the
// moduleNames array (moduleNames can be excluded from the route if includeNameInPath
// is false), and modulePath is the path generated by going up the keys of the route
// module which is described below.
// A routing module should return an object of the following structure:
/*
{
get: {
path: {
to: {
endpoint: function (req, res) {...}
}
},
"alternate/path/to/endpoint": function (req, res) {...}
},
post: {...},
delete: {...}
}
*/
// The root of the object, must be at least a get, post, or delete,
// this determines the endpoint type of the route. The path can be either
// built as a path from the keys of the object, or as a single key that
// is already the built path. You can also make a route object as so:
/*
{
get: function (req, res) {},
post: {...},
delete: {...}
}
*/
// in which case there is no additional modulePath added to the route
// when it is built.
module.exports = function(path, moduleNames, includeNameInPath) {
const router = express.Router();
moduleNames.forEach(function(name) {
let route = path;
if (includeNameInPath) {
route += name + "/";
}
console.log("Build routes for " + path + name);
let routeData = require("./routes" + path + name);
for (let endpointType in routeData) {
console.log("Build " + endpointType + " endpoints...");
let routes = routeData[endpointType];
if (typeof routes === "object") {
traverse(routes).forEach(function() {
if (this.isLeaf) {
let fullPath = route + this.path.join("/");
console.log(fullPath);
router[endpointType](fullPath, this.node);
}
});
} else {
console.log(route);
// There is only 1 path at root for the endpoint type
// Rather than traversing the object
router[endpointType](route, routes);
}
console.log("done\n");
}
});
return router;
};