The UrBlog

John's Ramblings about Software Development

Roll Your Own Controllers With Express and Require.JS

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.

There are cases where your URL does not match /controller/action. Grails allows you to setup a UrlMapping file that maps URLs to controllers. We could setup a similar file in JavaScript:

We can then loop thru the mappings and register them with Express:

With just Express, Require.JS and a few lines of JavaScript, I now have convention over configuration controllers

Comments