middl
A generic middleware library, inspired by Express and suitable for anything
Note all examples below use ES2015 syntax but the library should be able to run even in browsers back to IE9, as long as you're polyfilling the Promise object.
Why?
Because the middleware pattern is super useful! With this module you can even BYOE (Build Your Own Express) quite easily (see example below).
It also supports promises so your middleware can be async (see module usage for an example).
Installation
Install middl
using npm:
npm install --save middl
Usage
Module usage
const middl = require('middl');
const app = middl();
app.use((input, output) => {
output.prop = 1;
});
app.use((input, output) => {
return new Promise(resolve => {
setTimeout(() => {
output.prop += 1;
resolve();
}, 10);
});
});
app.use((input, output, next) => {
var start = new Date();
next()
.then(() => {
var ms = new Date() - start;
console.log('Done in %s ms', ms);
});
});
app.use(function *(input, output, next) {
var start = new Date();
yield next();
var ms = new Date() - start;
console.log('Done in %s ms', ms);
});
app.use(async (input, output, next) => {
var start = new Date();
await next();
var ms = new Date() - start;
console.log('Done in %s ms', ms);
});
app.use((err, input, output, next) => {
if (err) {
console.error(err);
} else {
next();
}
});
app.match({val: 'hello'}, (input, output) => {
output.response = 'world';
});
app.match({val: 'hello'}, (input, output) => {
output.response = 'you';
});
app.match({val: 'hi'}, (input, output) => {
output.response = 'there';
});
app.run({val: 'hello'}, {})
.then(output => {
});
Examples
Example BYOE
BYOE - Build Your Own Express
With Middl all it takes to create an Express like web server is the following code snippet.
Off course this is a quite limited feature set and API compared to the full Express library, but hopefully it shows how to use Middl in a creative way.
const http = require('http');
const middl = require('middl');
const app = middl({pathProperty: 'url'});
http.METHODS.forEach(method => {
app[method.toLowerCase()] = app.match({method});
});
app.all = (path, fn) => {
http.METHODS.forEach(method => {
app[method.toLowerCase()](path, fn);
});
return app;
};
app.get('/test', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('ok\n');
});
app.post('/test', (req, res) => {
res.writeHead(202, {'Content-Type': 'text/plain'});
res.end('accepted\n');
});
http.createServer(app).listen(3000);
API
middl(options)
Name | Type | Description |
---|
options | Object | Options |
Returns: app
options.pathProperty
Type: String
Used to enable the possibility to use a mount path when adding middleware (see example above).
app(input, output)
Name | Type | Description |
---|
input | Object | The input to the middleware stack, will be used as the first argument of each middleware (think of Express' req ) |
output | Object | The output to/from the middleware stack, will be used as the second argument of each middleware (think of Express' res ) |
The Express like app
function.
Returns: Promise
which is resolved when the whole stack of middleware have been run through, or the flow have been aborted by throwing an error/returning a rejected Promise or by not calling next
.
app.use([path, ], ...fn)
Name | Type | Description |
---|
path | String | An optional mount path for the middleware (only applicable if options.pathProperty is set) |
...fn | Function | The middleware function(s) |
The middleware function signature should be similar to that of Express, i.e: function ([err, ] input, output [, next]) { ... }
.
Returns: app
for chaining.
app.match(conditions [, path [, ...fn]])
Name | Type | Description |
---|
conditions | Object | The middleware will only be run if the current input matches this object |
path | String | An optional mount path for the middleware (only applicable if options.pathProperty is set) |
...fn | Function | The middleware function(s) |
The middleware function signature should be similar to that of Express, i.e: function ([err, ] input, output [, next]) { ... }
.
Returns: app
for chaining if ...fn
is provided, otherwise a partially applied function
will be returned, e.g:
app.match({method: 'GET'}, '/test', (req, res) => { ... });
const get = app.match({method: 'GET'});
get('/test', (req, res) => { ... });
How the conditions are matched
Each own property of the conditions
object are matched with the property with the same name in input
, in the following way:
If conditions[property]
is a:
- regular expression:
input[property]
must match the regular expression - function: the function will be called with
input[property]
as argument and should return a boolean
indicating if the property matches (true
) or not (false
) - otherwise:
input[property]
must equal (===
) conditions[property]
License
MIT © Joakim Carlstein