I’m a Grails developer at work, so I’ve gotten used to convention over configuration for controllers. I just create a class with a name that ends in Controller and place it the controller folder. Each method in the controller is an action and it allows me to access that method via /controller/action/id.
While Node and Express have full blown Rails copies (such as Geddy), I want something simpler. I prefer to use Require.JS to help me manage my dependencies. It includes a require method that allows me to load a module by name.
This gave me an idea. What if I could make a /controller/acton/id route in Express and use require to dynamically load the controller. I could then call the action on the controller as a key. It turns out it’s pretty simple:
Now any module in app/controller that has a method that takes a request and response can act as a controller with no configuration. This example responds to /health/index. Since we set it up to go to index when there’s no action, it will also respond to /health.
We can then loop thru the mappings and register them with Express: