A regular expression URL dispatcher for Connect
A really simple URL dispatcher for Connect or a plain Node.js HTTP Server. Allows arbitrarily nested regular expressions for matching URLs and calling an associated function.
var Connect = require'connect'dispatch = require'dispatch';ConnectcreateServerdispatch;
Or, using a vanilla HTTP Server:
var http = require'http';var server = httpcreateServerdispatch;serverlisten8080;
Dispatch can be used with a straight-forward object literal containing view functions keyed by URL. As you can see from the last URL in the list, captured groups are passed to the matching function as an argument.
You can also use :named parameters in a URL, which is just a more readable way of capturing ([^/]+). Named parameters are passed to the matched function in the same way as normal regular expression groups.
So far so predictable. However, it is also possible to nest these objects as you see fit:
This helps you tidy up the structure to make it more readable. It also makes renaming higher-level parts of the path much simpler. If we wanted to change 'user' to 'member', we'd now only have to do that once. Another advantage of being able to nest groups of URLs is mounting reusable apps in your site tree. Let's assume that 'user' is actually provided by another module:
Easy! A really lightweight and flexible URL dispatcher that just does the obvious.
Its also possible to define methods for URLs:
Just prefix the URL with the http method in uppercase followed by whitespace and then the path you want to match against. Nested URLs always match the last method defined in the tree. Because of this, you can use the following style for matching request methods, if you prefer:
A couple of implementation points:
I like to combine this with quip for rapid prototyping and just getting my ideas down in code:
var Connect = require'connect'quip = require'quip'dispatch = require'dispatch';var server = ConnectcreateServerquipdispatchrestext'hello world!';resjsonhello: 'world';;serverlisten8080;