express-middleware-utils
v0.1.2
Published
SafeAsync, SomeOf and EveryOf middlewares for ExpressJS
Downloads
6
Readme
Express util middlewares
Install
yarn add express-middleware-utils
Usage
SafeAsync - wrapping async handlers so they throw errors to express error handlers
import { safeAsync } from 'express-middleware-utils'
...
app.use(safeAsync(async (req,res) => {
// in case error is thrown it will be catched and passed to next so error handlers are called
}))
SomeOf - execute provided middlewares sequentially. Stops executing when middleware passes or throws fatal error. If all middlewares fail, throw error of last middleware in array or provided default error.
import { someOf, UnauthorizedError } from 'express-middleware-utils'
...
app.use(someOf(
[
jwtAuthMiddleware(), // It's executed first. If it passes, someOf calls next. If it throws fatal error, someOf calls next with that fatal error.
apiKeyAuthMiddleware(), // It's executed if first middleware thrown non-fatal error.
],
new UnauthorizedError(), // It's being thrown if none of provided middlewares passed. If error isn't provided, error of last middleware will be used.
)
)
EveryOf - passes if all provided middlewares pass.
import { everyOf } from 'express-middleware-utils'
...
app.use(everyOf(
[
jwtAuthMiddleware(), // It's executed first. If it passes, everyOf calls next middleware. If it throws error, everyOf calls next with that error.
hasRoles('ADMIN'), // It's executed only if previous middlewares passed.
])
)