express-switch
v0.1.2
Published
A pattern matching middleware for express
Downloads
8
Maintainers
Readme
express-switch
express-switch is a pattern matching middleware for express
Installation
$ npm install express-switch
Parameters
eSwitch(getter, pattern)
- getter (mandatory) a function that returns the value to match against the pattern
- pattern (mandatory) an object that describes the different routes to follow depending on the value returned by the getter
Getter
The getter is a function that is responsible to compute the value to match against the cases. This function can be synchronous or asynchronous.
Synchronous
The getter is synchronous when the number of parameters is less than 3. It has to return the value.
prototype
function (req, res) { /* ... */ return value; }
example
var express = require('express');
var eSwitch = require('express-switch');
var app = express();
// ...
app.use(eSwitch(
function(req, res){
return value; // here you have to return the value to match against the cases
},
{
case: {
CASE1: middleware1, // this will be executed if the getter returns 'CASE1'
CASE2: [middleware2, middleware3] // these will be execute if the getter returns 'CASE2'
},
default: middleware5 // this will be executed if the getter return neither 'CASE1' nor 'CASE2'
}
));
// ...
app.listen(3000);
Asynchronous
The getter is asynchronous when the number of parameters is more than 2. It has to forward the value to the done callback.
prototype
function (req, res, done) {
// ...
if (error) {
done(undefined, error);
} else {
done(value);
}
// ...
}
example
var express = require('express');
var eSwitch = require('express-switch');
var app = express();
// ...
app.use(eSwitch(
function(req, res, done){
something.doAsync(req, res, function(err, value){
if (err){
return done(undefined, err); // error forwarding
}
done(value); // you have to forward to the done callback the value to match against the cases
});
},
{
case: {
CASE1: middleware1, // this will be executed if the getter returns 'CASE1'
CASE2: [middleware2, middleware3] // these will be execute if the getter returns 'CASE2'
},
default: middleware5 // this will be executed if the getter return neither 'CASE1' nor 'CASE2'
}
));
// ...
app.listen(3000);
Return an Array
If the getter returns/forwards an Array all the values will be analized sequencially, unless one of the middlewares forwards an error.
Pattern
The pattern is an object with the following properties.
- case (mandatory) a lookup table of middlewares or arrays of middlewares.
- default (optional) the default route to follow if none of the cases matches.
prototye
var pattern = {
case : {
"value 1" : middleware1,
"value 2" : [middleware2, middleware3],
// ...
"value N" : middleware
},
default : middleware // optional
}