Artisan of Code

Projects

Artisan Delegator

A URL routing middleware for node.js.

Description

Delegator is a standalone library for request delegation in node.js inspired by pythons selector.

It provides a component for “RESTful” dispatching of requests to callbacks based on the URI path and HTTP request method as well as a connect middleware for automatic dispatching.

There is a very simple format for path matching expressions and there is also support for an external “mapping file” that can be used to express the mappings outside of your JavaScript code.

Example

var http = require('http')
  , delegator = require('artisan-delegator')()
  , widgets = require('./widgets')
  , server
  ;

delegator.add('/widget/{id:number}', {
  GET: function(req, res) {
    var widget = widgets.fetch(req.params.id)
      ;

    if (!widget) {

      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('404 Not Found');
    }

    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(widget));
  }
, PUT: function(req, res) {
    var body = []
      ;

    req.on('data', function (data) {
      body.push(data);
    });

    req.on('end', function () {
      widgets.store(req.params.id, JSON.parse(body.join('')));

      res.writeHead(204);
      res.end();
    });
  }
, DELETE: function(req, res) {
    widgets.delete(req.params.id);

    res.writeHead(204);
    res.end();
  }
});

server = http.createServer(function(req, res) {
    delegator(req, res, function(err) {
      var status = err && err.status || 404
        ;

      res.writeHead(status, {'Content-Type': 'text/plain'});
      res.end('NOT FOUND');
    });
});

server.listen(3000);

Install

To install Artisan Delegator from npm:

npm install artisan-delegator

History

1.0.0

Initial Release

Documentation

Documentation is hosted by Read the Docs

Source Code

Source code and issue tracking is available on my bitbucket account and the code is mirrored on github.

© 2010-2012 Daniel Knell