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

conditional-middleware

v0.2.0

Published

Conditional, composable middleware for connect, express, and other soon-to-be available server modules.

Downloads

156

Readme

conditional-middleware

This very lightweight module allows you to compose chains of middleware based on a condition. If the condition fails, the middleware chain does not execute - not even as a wrapper around next() calls.

npm install conditional-middleware --save

Supported Middleware

  • connect-friendly - Express, flatiron/union, et al.

    // connect-friendly middleware:
    (req, res, next) => { ... }
    (err, req, res, next) => { ... } //-> must have exactly 4 arguments
  • Koa - Since KOA is so different, you must require a different file. Everything else is the same. Note - you must use use Node 7.6+ or Babel per Koa's requirements.

    // koa users must include like this
    const conditional = require('conditional-middleware/koa');
       
    // koa style middleware
    (ctx, next) => { ... }

Basic Usage


Koa Users: The following examples use express. Anywhere you see 'express' can be replaced with 'koa'. Anywhere you see express-style middleware can be replaced with koa-style middleware. Also, remember you need to do this:

const conditional = require('conditional-middleware/koa');

In the following example, if shouldHandleRequest returns false, middleware1 and middleware2 will not execute.

const express = require('express');
const conditional = require('conditional-middleware');

function shouldHandleRequest (req) {
	return Math.random() > 0.5;
}

const app = express();
app.use(conditional(shouldHandleRequest, [ 
	middleware1, 
	middleware2 
]));

Condition methods can return a promise

In the example above, shouldHandleRequest can return a promise. The promise must resolve to truthy or falsy. You should never use reject to mean "condition failed".

function shouldHandleRequest (req) {
    return Promise.resolve( Math.random() > 0.5 );
}

Use a "context" for if/else if behavior

Consider a situation where you want to have multiple conditions but only want the first one that returns true. This type of behavior is availble by creating a "context". In the following example, as soon as one condition returns true, none of the other conditions are checked.

const express = require('express');
const conditional = require('conditional-middleware');

function isGithubWebhook (req) {
	return req.get('x-github-event');
}
function isBasicAuth (req) {
	return req.get('Authorization').indexOf('Basic') === 0;
}

const app = express();
conditional.createContext(_conditional => {
	// now use _conditional
	app.use(_conditional(isGithubWebhook, [
		validateGithubRequest,
		processGithubWebhook, 
		middleware_1,
		...
	]);
	// else if
	app.use(_conditional(isBasicAuth, [
		validateAuthCredentials, 
		middleware_2,
		...
	]);
	// else
	app.use(_conditional(() => true, [
		sendUnauthorizedResponse
	]);
});

But what if the condtion returns false?

Other modules like express-conditional-middleware accept a "failure" function for when the condition fails. However, this is not necessary becuase the very next middleware will always run when the condition fails. Continuing with the basic example above, here is how you might handle a simple failure scenario:

const express = require('express');
const conditional = require('conditional-middleware');

function alwaysFalse (req) {
	req.foobar = true; // set a custom property
	return false;
}

const app = express();
app.use(conditional(alwaysFalse, [ 
    thisWillNeverRun
]));

// the very next middleware will run
app.use((req, res, next) => {
	if (req.foobar) {
	    // something went foobar
	}
});

What about nesting?

Yup, that works too! The condtional function will always return middleware, allowing you use it anywhere where you would use normally use middleware.

const express = require('express');
const conditional = require('conditional-middleware');

const app = express();
app.use(conditional(() => true, [ 
    (req, res, next) => {
    	req.foo = true;
    	next();
    },
    conditional(() => true, [
    	(req, res, next) => {
    		req.bar = true;
    		next();
    	},
    	conditional(...)
    ]),
    (req, res, next) => {
    	assert.ok(req.foo, 'foo is set');
    	assert.ok(req.bar, 'bar is set');
    	next()
    }
]));

What lies ahead?