flat-route

Simplest regex router for connect (56 lines of code) with the support of defining route specific logic.

npm install flat-route
1 downloads in the last week
4 downloads in the last month

Description

Simplest router for connect (56 lines of code) which supports route specific logic. See usage below.

Installation

npm install flat-route

Usage


// Controller, action.
var users = {
  create: function(req, res, next) {
    // Do model job.
    next();
  }
};

// Routes.
var routes = [
  ['POST', /^\/users$/, users.create, {
    auth: true
  }]
];

var connect = require('connect');
var flatRoute = require('flat-route')(routes);

var app = connect()

  // First we attach (at this point, flatRoute sets the req.route)
  .use(flatRoute.attach) 

  // No we can create our custom route logic ... (input validation, auth logic, etc.)
  // Little example below:
  .use(function(req, res, next) {
    if (req.route.data.auth) {
      // Check for session auth?
    }

    next();
  })

  // Finally we apply, which calls the callback of the route (3th array element of a route).
  .use(flatRoute.apply);

app.listen(3000);

Options

By default, if no matching route was found, flatRoute will throw a 404 and end the request, however you can overwrite this logic. See the example below:


var flatRoute = require('flat-route')(routes, {
  notFound: function(req, res, next) {
    // Do my custom 404 logic here.
  }
});

// ... continue as connect middleware (see Usage)
npm loves you