Miss any of our Open RFC calls?Watch the recordings here! »

tilt-router

0.0.4 • Public • Published

tilt-router Build Status

Class based HTTP router

Compatible with Express 4, Hapi or simple HTTP server.

Lightweight, has only debug and path-to-regexp dependencies.

This module is a follow-up to ES6 Class based Express routing blog post.

Installation

npm install mklabs/tilt-router -S

Usage

Instead of writing app.get('/', function() {}); or server.router({ method: 'GET', path: '/', handler: function() {}}) to define request handlers, you use a Class to hold methods registered as route handlers to the underlying framework, Express or Hapi.

Additionnaly, it implements a simple routing mechanism with raw HTTP server.

import TiltRouter from 'tilt-router'
 
class Router extends TiltRouter {
  get routes() {
    '/': 'index'
  }
 
  index(req, res) {
    console.log('Incoming request:', req.url);
    return res.send('Response from server');
  }
}

Express

var app = require('express')();
var router = new Router(app);
app.listen(3000);

Or

var app = require('express')();
app.use(Router.middleware(app));
app.listen(3000);

Standard http server

var router = new Router();
router.listen(3000);

Or

var http = require('http');
http.createServer(Router.middleware()).listen(3000);

Or

Router.createServer().listen(3000);

Or

Router.listen(3000);

Documentation

Router

API

Router.createServer().

Router.createServer().listen(PORT, done);

Router.listen().

Router.listen(PORT, done);

Router.create().

var router = Router.create();
assert.ok(router instanceof Router);

Router.dispatch() - express middleware.

app.use(Router.middleware(app));

Router.dispatch() - HTTP server.

http.createServer(Router.middleware());

App extends Router.

class App extends Router {
  get routes() {
    return {
      '/': 'index'
    };
  }
  index(req, res, next) {
    return res.end('OK');
  }
}
var app = new App();
app.listen(PORT, done);

HTTP response

GET /.

request(this.app)
  .get('/')
  .expect('OK')
  .expect(200, done);
var server = TestApp.createServer();
request(this.app)
  .get('/aoizheuaziouh')
  .expect(404, done);

MIT  ·  mkla.bz  ·  @mklabs

Keywords

none

Install

npm i tilt-router

DownloadsWeekly Downloads

10

Version

0.0.4

License

MIT

Last publish

Collaborators

  • avatar