You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

middleware-async

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

middleware-async

A handy tool to work with async/promise express middleware

0.0.3
npmnpm
Version published
Weekly downloads
1.5K
-15.62%
Maintainers
1
Weekly downloads
 
Created
Source

Async Middleware Build Status

NPM

A handy tool to write async/promise style middleware for express, connect-like.

Why this tool is needed?

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 middleware returning Promise.

However, express does not support if promise returned by the middleware is rejected. The followings middlewares will never be called.

Solution is simple by wrapping the middleware with

import middlewaareAsync from 'middleware-async'
app.use(middlewaareAsync(async (req, res, next) => {
  req.user = await User.findById(req.params.id).exec()
  next()  
}))

How to install

Install it via npm or yarn

npm install --save middleware-async
#or
yarn add middleware-async

API

  • middlewaareAsync(middlware): return a middleware that covers error thrown or error that is rejected by middleware
  • combineMiddlewares(list of middlewares or list of list of middlewares): combine many middlewares into one middleware. Very useful for testing
  • middlewareToPromise: convert express-style middleware into Promise
  • combineToAsync: combination of middleewareToPromise and combineMiddlewares

Sample usages

import middlewareAsync, {combineMiddlewares, combineToAsync, middlewareToPromise} from 'middleeware-async'

describe('combineMiddlwares', () => {
  it('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).to.equal(2)
  })
})

Keywords

connect

FAQs

Package last updated on 28 Aug 2018

Did you know?

Socket

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.

Install

Related posts