classy-router
Class based HTTP router
Lightweight, has only debug and
path-to-regexp dependencies.
It is compatible with Express 4, Hapi or simple HTTP server.
This module is a follow-up of ES6 Class based Express
routing blog post.
Installation
npm install classy-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 ClassyRouter from 'classy-router'
class Router extends ClassyRouter {
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