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

1.1.0
npmnpm
Version published
Weekly downloads
1.3K
-22.1%
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 handler returning Promise.

However, express does not support if promise returned by the handler is rejected. The following handlers will never be called.

Solution is simple by wrapping the handler 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

How to install

Install it via npm or yarn

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

API

  • middlewaareAsync(middlware): returns a handler that covers error thrown or error that is rejected by handler via the next function. The next function is called at most once.
  • combineMiddlewares(list of handlers or list of list of handlers with any depth): combine many handlers into one handler. Very useful for testing You can combine your handlers like combineMiddlewares([mdw1, mdw2], [[mdw3], [mdw4, [mdw5, mdw6]], mdw7], mdw8). The function will take care of expanding parameters.
  • middlewareToPromise: convert express-style handler into Promise by appending the next handler to the input handler.
  • combineToAsync: combination of middleewareToPromise and combineMiddlewares

Sample usages

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)
  })
})

Keywords

connect

FAQs

Package last updated on 16 Feb 2020

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