dispatchington

Trie-based URL and Method Routing for Node.js

npm install dispatchington
6 downloads in the last week
13 downloads in the last month

Dispatchington Build Status

Dispatchington is a trie-based URL and method router for Node.js based on routington. It can almost be used as a drop-in replacement. For information on its motivations, read about The Imperfections of Express.

When should you use this?

  • Want your server to conform to HTTP specs
  • Want to decouple your app from Connect/Express
  • Prefer a more modular router
  • Prefer explicit routing
  • You repeat a lot of route definitions
  • You want structure to your URL routes - routes are stored in a branch tree
  • You want to programmatically edit or change your routes
  • You don't want route definition order to matter

Features

  • Supports the OPTIONS method automatically
  • Supports 405 Method Not Allowed automatically
  • Supports 501 Not Implemented automatically, assuming you use the middleware
  • Allows you to "define" middleware stacks for easy re-use
  • Faster than linear, regular-expression-based routers

API

Mounting to Connect/Express

var dispatchington = require('dispatchington')
var router = dispatchington()

To mount the middleware:

var app = express()
app.use(router.implementedMethods)
// static stuff
// cookie stuff
// session stuff
app.use(router.dispatcher)
// 404 handler
// error handler

Standalone

You can still use the router without Express or Connect:

var dispatcher = router.dispatcher
// Map of methods implemented by the server.
// All methods are lowercased.
var methods = router.methods

// ...
// Define routes
// ...

http.createServer().on('request', function (req, res) {
  if (!methods[req.method.toLowerCase()]) {
    res.statusCode = 501
    res.end('Not Implemented')
    return
  }

  dispatcher(function (req, res, next) {
    if (err) {
      res.statusCode = err.status || 500
      res.end(err.message || 'Internal Server Error')
      return
    }

    // If this point is reached,
    // no route has been matched
    res.statusCode = 404
    res.end('Not Found')
  })
}).listen(process.env.PORT || 80)

Defining middleware stacks

You can define stacks of middleware, either a single function or an array of functions, with a name. These stacks can then be referenced by name.

After defining the following stacks:

router.define('compress', connect.compress())
router.define('session', [
  connect.cookieParser(),
  connect.cookieSession()
])

The following simplified stack:

router.get('/', 'compress', 'session')

is equivalent to all of the following:

router.get('/', connect.compress(), connect.cookieParser(), connect.cookieSession())
router.get('/', connect.compress(), [
  connect.cookieParser(),
  connect.cookieSession()
])
router.get('/', [
  connect.compress()
  connect.cookieParser(),
  connect.cookieSession()
])

The idea is that you turn your middleware stacks into legos. You can define them early in your app, then re-use them throughout your routes without require()ing each of them from an external "common" module. It will also make your routes much more readable as, ideally, it could look something like this:

router.get('/',
  'compress',
  'cache if visitor',
  'accept html only',
  'retrieve session',
  'retrieve user',
  'check if allowed',
  'parse body',
  handler
)

function handler(req, res) {
  res.render('homepage')
}

You will know exactly what happens before you execute the handler. You can use or don't use specific middleware very easily depending on the URL or method matched.

Defining routes

For information on how the routing strings actually work, view routington's documentation.

There are two ways to create a route. The first is Express' method-first way:

router.get('/things', 'compress', 'session', handler, ...)
router.post('/things', 'compress', 'session', handler, ...)
router.put('/things', 'compress', 'session', handler, ...)

The other is by defining a route, then adding stacks based on the method:

router.route('/things')
.get('compress', 'session', handler, ...)
.post('compress', 'session', handler, ...)
.put('compress', 'session', handler, ...)

In both versions, you can define multiple routes at the same time:

router.route(
  '/things',
  '/thing/:id'
)
.get('compress', 'session', handler, ...)
.post('compress', 'session', handler, ...)
.put('compress', 'session', handler, ...)

router.get([
  '/things',
  '/thing/:id'
], 'session', handler, ...)

Parameter matching

If you define a route like so:

router.get('/thing/:id', handler)

You can retrieve the value of id just like in Express:

function handler(req, res, next) {
  req.id = req.params.id
  next()
}

Accessing the trie

The trie, specifically the routington instance, is accessible at router.trie. You can manipulate it however you'd like. View its documentation for more information.

Unsupported Express features

  • Wildcard routes are not supported. The purpose of this router is to make it easier for you to be explicit.
  • app.all is not supported. Simply define a stack and use it in every method. npm install methods for a list of all possible methods.
  • Regular expressions (as a variable type) are not supported as input arguments. If you want to use regular expressions, just stick with Express' router.

License

The MIT License (MIT)

Copyright (c) 2013 Jonathan Ong me@jongleberry.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

npm loves you