
Security News
Bun 1.2.19 Adds Isolated Installs for Better Monorepo Support
Bun 1.2.19 introduces isolated installs for smoother monorepo workflows, along with performance boosts, new tooling, and key compatibility fixes.
middleware-async
Advanced tools
A handy tool to write async/promise style middleware for express, connect-like.
Lets check at this code
app.use(async (req, res, next) => {
req.user = await User.findById(req.params.id).exec()
next()
})
The next()
will be executed after User.findById(...).exec()
is fulfilled because express allow middlewares returning a promise.
However, express does not support if the promise returned by the middleware is rejected. The following middlewares will never be called, and the response will never be returned to the client.
The solution is simple by wrapping the middleware with
import {asyncMiddleware} from 'middleware-async'
app.use(asyncMiddleware(async (req, res, next) => {
req.user = await User.findById(req.params.id).exec()
next()
}))
Note that once the next
function is called, following errors will not be thrown, and vice versa.
Example:
import {asyncMiddleware} from 'middleware-async'
app.use(asyncMiddleware(async (req, res, next) => {
next()
throw new Error('my error')
}))
the error new Error('my error')
will not be thrown because the next
function is called.
Or
import {asyncMiddleware} from 'middleware-async'
app.use(asyncMiddleware((req, res, next) => {
return Promise((resolve, reject)=> {
reject()
setTimeout(() => next(new Error('next error')), 0)
})
}))
the new Error('next error')
error will not be thrown because the promise is already rejected
Install it via npm or yarn
npm install --save middleware-async
#or
yarn add middleware-async
asyncMiddleware(middlware)
: returns a middleware that covers the error thrown (throw err
) or rejected (next(err)
) by middlewares. The next parameter of the returned middleware is called at most once.Sample usage:
app.use(asyncMiddleware(async (req, res, next) => {/*middleware code*/}))
combineMiddlewares(middleware, list of middlewares, or list of middlewares with any depth)
: combine one or many middlewares into one middlware. Very useful for testing.You can use this API like combineMiddlewares(mdw)
or combineMiddlewares([mdw1, mdw2], [[mdw3], [mdw4, [mdw5, mdw6]], mdw7], mdw8)
. The function will take care of expanding parameters.
Note that this function does not wrap the middelware with asyncMiddleware
. If the middleware returns a promise, you need to wrap the middleware manually otherwise the error will never be caught.
middlewareToPromise
: convert express-style middlware to a function which returns a promise.await middlewareToPromise(mdw)(req, res)
is rejected if the middleware mdw
throws error (in express/connect-like style), otherwise the promise is resolved normally.
combineToAsync
: combination of middleewareToPromise
and combineMiddlewares
Example: await combineToAsync(mdw)(req, res)
import {asyncMiddleware, combineMiddlewares, combineToAsync, middlewareToPromise} from 'middleeware-async'
describe('combineMiddlwares', () => {
test('should go through all middlewares', async () => {
const req = {val: 0}
await combineToAsync([
async (req, res, next) => {
await Promise.resolve()
req.val += 1
next()
},
(req, res, next) => {
req.val++
next()
},
])(req)
expect(req.val).toBe(2)
})
})
Check test directory for more sample usages.
FAQs
A handy tool to work with async/promise express middleware
The npm package middleware-async receives a total of 1,024 weekly downloads. As such, middleware-async popularity was classified as popular.
We found that middleware-async demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2.19 introduces isolated installs for smoother monorepo workflows, along with performance boosts, new tooling, and key compatibility fixes.
Security News
Popular npm packages like eslint-config-prettier were compromised after a phishing attack stole a maintainer’s token, spreading malicious updates.
Security News
/Research
A phishing attack targeted developers using a typosquatted npm domain (npnjs.com) to steal credentials via fake login pages - watch out for similar scams.