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:{ ... }{ ... } //-> 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 thisconst conditional = ;// koa style middleware{ ... }
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 = ;
In the following example, if shouldHandleRequest
returns false, middleware1 and middleware2 will not execute.
const express = ;const conditional = ; { return Math > 05;} const app = ;app;
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".
{ return Promise;}
if/else if
behavior
Use a "context" for 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 = ;const conditional = ; { return req;} { return req === 0;} const app = ;conditional
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 = ;const conditional = ; { reqfoobar = true; // set a custom property return false;} const app = ;app; // the very next middleware will runapp;
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 = ;const conditional = ; const app = ;app;
What lies ahead?
- A new API? - Cast your opinions here