2.7 KiB
2.7 KiB
MiddlewareHandler
MiddlewareHandler manages custom middlewares in the same way as how Express/Connect does.
var MiddlewareHandler = require('middleware-handler');
var handler = new MiddlewareHandler();
.use(function(a, b, next) {
handlerconsole.log(a, b); // foo bar
next();
;
}).handle(['foo', 'bar']); handler
Installation
$ npm install middleware-handler
Example
Integration with Socket.io
Parsing cookie from handshake’s data with the authorization.
var cookieParser = require('express').cookieParser('secret');
var handler = new MiddlewareHandler();
.use(function(handshakeData, next) {
handler// handshakeData has almost the same attributes with request object.
cookieParser(handshakeData, {}, next);
;
})
var io = require('socket.io').listen(8080);
.set('authorization', function(handshakeData, callback) {
io.handle([handshakeData], function(err) {
handlerconsole.log(handshakeData.cookies);
callback(err, !err);
;
}); })
Documentation
#use(middleware)
middleware
accepts variable arguments and a
callback.
var handler = new MiddlewareHandler();
.use(function(arg, next) {
handlervar err;
// do some stuff
next(err); // optionally accepts an error object
; })
.use(function(arg, next) {
handlernext(null, 'foo'); // arguments will be passed to a next middleware
;
}).use(function(arg, next) {
handlerconsole.log(arg); // 'foo'
next();
; })
#handle([args], [callback])
Invokes middlewares.
var handler = new MiddlewareHandler();
.use(function(a, b, next) {
handlerconsole.log(a, b); // 'foo bar'
next();
;
}).handle(['foo', 'bar'], function(err) {
handler// after calling all middlewares
; })
#compose([callback])
Creates a function which invokes middlewares.
var handler = new MiddlewareHandler();
.use(function(a, b, next) {
handlerconsole.log(a, b); // 'foo bar'
next();
;
})
var fn = handler.compose(function(err) {
// after calling all middlewares
;
})fn('foo', 'bar');
#clear()
Clear all middlewares from the stack.
var handler = new MiddlewareHandler();
.use(function() {});
handlerconsole.log(handler.stack.length); // 1
.clear();
handlerconsole.log(handler.stack.length); // 0
compose(middlewares…)
Creates a function which invokes the passed middlewares.
function middleware(a, b, next) {
console.log(a, b); // 'foo bar'
next();
}
var fn = MiddlewareHandler.compose(middleware, function(a, b) {
console.log(a, b); // 'foo bar'
;
})fn('foo', 'bar');
License
MIT