Skip to content

Instantly share code, notes, and snippets.

@sclark39
Created March 5, 2017 23:57
Show Gist options
  • Save sclark39/8e4251d07e0481571d81b51c5d0d1076 to your computer and use it in GitHub Desktop.
Save sclark39/8e4251d07e0481571d81b51c5d0d1076 to your computer and use it in GitHub Desktop.
// Define the routes, which we will procedurally load
const routes =
{
get: // body data not allowed in GET
[
{ path: '/', action: 'HelloWorld' },
{ path: '/http', action: 'TestHTTP' },
{ path: '/echo', action: 'EchoRequest' },
]
}
var gActions = {}
// Collect all route action definitions
var normalizedPath = require("path").join(__dirname, "routes"); // get the full path for the ./routes folder
require("fs").readdirSync(normalizedPath).forEach(function(file) { // run a function on each file name found in the ./routes folder
console.log( `Found actions: ${file}` )
var actions = require("./routes/" + file); // load the file by name out of the routes folder, as javascript
var action_names = []
actions.forEach( function( action ) // assume the module.exports for these files is an array of elements. Run a function on each element.
{
if ( gActions[action.action] ) // see if an action by this name was already found in another file
{
console.error( `Reimplementing action '${action.action}' in ${file} is not allowed` )
}
else
{
gActions[action.action] = action.run // save a reference to the function which should handle actions by this name
action_names.push( action.action ) // only needed for the log print at the end, to have nice single-line output of all the actions
}
})
console.log( ` - ${action_names.join(', ')}`)
});
// Apply to the express app
Object.keys(routes).forEach( function( method ) // for each method in the routes array, run a function
{
routes[method].forEach( function(obj) // for each element in the array for this method, run a function
{
if ( !gActions[ obj.action ] ) // did we find a function to handle this action in the previous step?
{
console.warn( `No action found for ${method} '${obj.path}' with name '${obj.action}'` )
}
else
{
app[method]( obj.path, gActions[ obj.action ] ) // register this function with the express app
// This works by using array lookup to call the 'get' function from app procedurally. So effectively, this is calling
// app.get( path, function handler )
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment