Self-describing routes in node/express
Here’s a small trick we’ve found useful in developing a web service layer for Vyclone using node and express. One of the pain points in building against a web service is documentation of the API - the developer of the api has to remember to write doc comments, and keep them up to date as the api evolves; the build system needs to know about generating and publishing the API docs; and the developer of the client of the API has to go get the generated documentation for the particular build they’re developing against.
Express routes are defined using functions on the server object that correspond to the HTTP verbs - get, post, del and so on. We can use the functional capabilities of JavaScript to wrap these functions with versions that take an additional, initial parameter, a string documenting the use of that route. Here’s a version which adds the function-wrapping function as a method of the server instance, and encapsulates the data which we’ll use to render a documentation page inthe server object itself:
If you’re not familiar with the JavaScript idioms used here, some points to note:
- oldRouteMethod is declared before, but used inside the anonymous function. JavaScripts lexical scoping means that it’s value will be the object representing the original express route method (get, post etc) wrapped by the new function
- The pattern used by express to define the route can be a string or a regular expression object, hence the
toString()
call before it’s used as a key into the object holding the documentation strings - When the old route method is called, it’s passed all but the first argument to the new function. Express lets you provide any number of filters before the function that actually implements the route, so we take the
arguments
object and slice it by calling Array’s slice method (defined in the Array prototype), but with thearguments
object as the first parameter, which makes it the this object inside the call to slice.
Calling the method to replace the existing route methods is simple:
And documenting the methods themselves is subsequently straightforward:
It’s then a simple matter to provide a template to render the routes in an html page, and add a route (documented, of course) to view the page:
Our app developers can now see at a glance on the server they’re using for development which routes are available, their URL patterns and parameters.