0.2.0 • Published 11 years ago

k-router v0.2.0

Weekly downloads
1
License
-
Repository
github
Last release
11 years ago

K-Router

K-Router is a simple Class based router Connect middleware. In other words, it ehances the default Connect router (app.use('/url', fn)) to do more advanced routing to methods on instance object by router.route('/url', controller, 'action', 'GET'). The URLs work mostly like Expresses routing engine, it supports named and optional parameters, regex urls and can be bound to one HTTP verb at a time. It goes further than Expresses router in the following ways though:

  • You always pass an instance object, followed by a function name - which allows for late binding to the functions. By converse, Express has no kind of class binding, meaning you need to manually do this.
  • By specifying a URL route attached to a HTTP verb (e.g GET) all other verbs (e.g PUT POST DELETE) return 405 errors. This is how your website should behave. Also, all 405s will send a proper Allow header, saying what verbs are available. By converse, Express does nothing with other verbs, and so they 404.
  • It captures the 90% usecase by specifying .router.resources('/url', controller) and .router.resource('/url', controller) which automatically binds REST pattern routes, very similar to Rail's Routing::Mapper:: Resources. By converse, Express does not offer this and so you have to do these manually.

Usage

As it is a Middleware, you need to plug it into Connect or Express like so:

var connect = require('connect'),
    router  = require('k-router');

// All configuration options are completely optional and have defaults.
var app = connect()
    .use(router({
        strict: false // Allows URLs to have trailing / in URLs. Default: false,
        sensitive: false // Makes URLs case sensitive. Default: false,
        errorHandlers: { // Default set of error handlers (come provided)
            405: <function>
        },
        resourceActions: { // Default set of resource action names (see resources)
            ...
        }
    }));

Declaring routes

Normal routes mostly offer the same functionality you get from Express routes:

// Require a "Controller" (MVC) or "View" (MVT) that is a proper class we will
// use for routing:
var ViewClass = require('./users.view.js'),
    router    = require('k-router');

router.route('/users/:id', ViewClass, 'showUser', 'GET')
      .route('/users/:id', ViewClass, 'editUser', 'PUT');

The above example will send GET requests to "/users/:id" to ViewClass.showUser and PUT requests to that same url to ViewClass.editUser. For all other requests to that URL (HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT & PATCH) it will respond with "405 - Method Not Allowed" with an Allowed header of GET, PUT, just like RFC2616 says.

Declaring resources

Resources are a shortcut to declaring many routes. They follow the CRUD pattern, and are similar to how Rail's resources work. Resources come in two flavours, .resource() and .resources(). The plural .resources() binds the list, create, new, show, update, destroy, edit actions, while the singular .resource() binds the show, create, update, destroy, new, edit actions. If one of those actions doesn't exist on the controller, then the route isn't bound. See the handy table below for how these get mapped to different urls:

Resources (Plural, .resources())

VerbUrlController ActionDescription
GET/urlController#listDisplay a list of all items in a resource
POST/urlController#createCreate a new item
GET/url/newController#newHTML form for creating new items
GET/url/:idController#showDisplay a specific item
PUT/url/:idController#updateUpdate a specific item
PATCH/url/:idController#updateUpdate a specific item
DELETE/url/:idController#destroyDelete a specific item
GET/url/:id/editController#editHTML form for editing an item

Resource (Singular, .resource())

VerbUrlController ActionDescription
GET/urlController#showDisplay the singular resource
POST/urlController#createCreate a new resource like this
PUT/urlController#updateUpdate a specific item
PATCH/urlController#updateUpdate a specific item
DELETE/urlController#destroyDelete a specific item
GET/url/newController#newHTML form for creating new items
GET/url/editController#editHTML form for editing an item

Notes:

  • The New and Edit urls are used for presenting the user an HTML form, while the others are used as HTML and API (e.g JSON or XML) responses.
  • The difference between PUT and PATCH (according to the RFC) is that PUT should take an entire resource's data (i.e the whole record) while PATCH can update some or all parameters (i.e some of the record). In reality this makes little difference, so both are routed to the same action.
  • If you don't like any of the action names, you can remap them using the configuration option resourceActions. E.g:
    app.use(router({ resouceActions: {
      show: 'index', create: 'makenew', 'update': 'put'
    }}))
// Require a "Controller" (MVC) or "View" (MVT) that is a proper class we will
// use for routing:
var ViewClass = require('./users.view.js'),
    router    = require('k-router');

router.route('/users/:id', ViewClass, 'showUser', 'GET')
      .route('/users/:id', ViewClass, 'editUser', 'PUT');

LICENSE

MIT