middleware-if-unless
Invokes connect-like middleware if / unless routing criteria matches. Inspired on express-unless module.
Main features
- Advanced routes matching capabilities. Uses find-my-way or any compatible router to match the routes.
iff
: execute middleware only if the routes matches. Ideal use case: API gateways (see: k-fastify-gateway)unless
: execute middleware always unless the routes matches.- Arbitraty chaining of iff -> unless of vice-versa.
- Low overhead, crazy fast implementation.
Usage example
How to extend any connect-like middleware:
const iu = require('middleware-if-unless')()
const middleware = function (req, res, next) {
res.body = 'hit'
return next()
}
iu(middleware)
unless
Execute middleware unless routing restrictions matches:
const app = require('express')()
app.use(middleware.unless([
'/not/allowed/to/hit'
]))
...
In this example, all requests except [GET] /not/allowed/to/hit
will cause the middleware to be executed.
if
Execute middleware only if routing restrictions matches:
const app = require('express')()
app.use(middleware.iff([
{
methods: ['POST', 'DELETE', 'PUT', 'PATCH'],
url: '/tasks/:id'
}
]))
...
In this example, only a [POST|DELETE|PUT|PATCH] /tasks/:id
request will cause the middleware to be executed.
Chaining
You can optionally chain iff -> unless or vice-versa:
app.use(middleware
.iff(req => req.url.startsWith('/pets'))
.iff([
'/pets/*',
'/pets/:id/*'
]).unless([
'/pets/:id/owners',
{
url: '/pets/:id', methods: ['DELETE']
}
]).unless(req => req.url.endsWith('.js'))
)
Configuration
module
const iu = require('middleware-if-unless')(
{
}
,
function(opts){}
)
iff / unless
Both methods share the same configuration format:
- routing criteria is a function
middleware.iff(req => req.url.startsWith('/pets'))
- routing criteria is an array of routes
middleware.iff([
'/login',
{
methods: ['DELETE', 'POST', '...'],
url: '/tasks/:id/*'
}
])
- routing criteria is an object
middleware.unless({ endpoints: [
'/login',
{
methods: ['DELETE', 'POST', '...'],
url: '/tasks/:id/*'
}
]})