npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

middl

v0.4.0

Published

A generic middleware library, inspired by Express and suitable for anything

Downloads

13

Readme

middl

middl logo

Build status Coverage Status NPM version XO code style

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();

// a sync middleware
app.use((input, output) => {
	output.prop = 1;
});

// an async middleware
app.use((input, output) => {
	// Faking a time consuming task...
	return new Promise(resolve => {
		setTimeout(() => {
			output.prop += 1;
			resolve();
		}, 10);
	});
});

// a time measuring logger:
app.use((input, output, next) => {
	var start = new Date();
	next()
		.then(() => {
			var ms = new Date() - start;
			console.log('Done in %s ms', ms);
		});
});
// or even prettier with generator functions:
app.use(function *(input, output, next) {
	var start = new Date();
	yield next();
	var ms = new Date() - start;
	console.log('Done in %s ms', ms);
});
// or when using Babel and async/await:
app.use(async (input, output, next) => {
	var start = new Date();
	await next();
	var ms = new Date() - start;
	console.log('Done in %s ms', ms);
});


// an error handling middleware
app.use((err, input, output, next) => {
	if (err) {
		console.error(err);
		// by not calling next() we abort the chain
	} else {
		next();
	}
});

// conditional middleware
// this will be run because the conditions ({val: 'hello'}) matches the input:
app.match({val: 'hello'}, (input, output) => {
	output.response = 'world';
});
// this will *not* be run because the former middleware did not call next:
app.match({val: 'hello'}, (input, output) => {
	output.response = 'you';
});
// this won't run because the conditions ({val: 'hi'}) does not match the input
app.match({val: 'hi'}, (input, output) => {
	output.response = 'there';
});

// pass in the initial `input` and `output` objects
// and run the middleware stack:
app.run({val: 'hello'}, {})
	.then(output => {
		// output.prop === 2
		// output.response = 'world'
	});

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');

// Make middl more Express like by using `url` as the property to match paths with:
const app = middl({pathProperty: 'url'});

// Adding all app.METHOD() functions à la Express:
http.METHODS.forEach(method => {
	app[method.toLowerCase()] = app.match({method});
});
// Also the app.all():
app.all = (path, fn) => {
	http.METHODS.forEach(method => {
		app[method.toLowerCase()](path, fn);
	});
	return app;
};

// A route handler for requests to: GET /test
app.get('/test', (req, res) => {
	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('ok\n');
});
// A route handler for requests to: POST /test
app.post('/test', (req, res) => {
	res.writeHead(202, {'Content-Type': 'text/plain'});
	res.end('accepted\n');
});

// Make the middle app web server listen on port 3000:
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:

// this:
app.match({method: 'GET'}, '/test', (req, res) => { ... });
// is the same as this:
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