0.1.2 • Published 4 years ago

async-express-helpers v0.1.2

Weekly downloads
32
License
MIT
Repository
github
Last release
4 years ago

Async Express Helpers

Helpers to build async handlers/middleware for express

npm Build Status codecov

This plugins offer two helpers to assist you in building expressjs@4 applications with new async features of javascript.

It does so by providing an asyncHandler and a asyncMiddleware helper.

Both helpers will handle promise exceptions and automaticaly call the next callback.

API

Retrieve both helpers from the module:

  const {asyncHandler, asyncMiddleware} = require('async-express-helpers');

and there you go.

asyncHandler

  app.get('/some-path', asyncHandler(async (req, res) => {
      // do something async and then
      res.send('Hello 👋');
    })
  );

asyncMiddleware

If ever exception occured in the handler (ejected promise), next is called with the exception. Otherwise in the "happy path", you have the possibility to activate an implicit next mode which tell wrapper to take care to call next.

Here are the two modes:

  • explicit next mode (default): in this (default) mode, you either need to call next yourself (as you would normaly do). You can also return true (or any truthy value) from the middleware and the wrapper will next() for you.

      app.use(
        asyncMiddleware(async (req, res, next) => {
          // do something with the req, res...
          next(); // or "return true;" instead
        })
      );
  • implicit next mode: in this mode, the wrapper will automatically call next when the wrapped handler will return or resolve. If needed you can cancel this by returning false from wrapped middleware.

    app.use(
      asyncMiddleware(async req => {
        // do something here, adding something for req for example
        // return false if you want to cancel implicit next
      }, true)
    );

Example

A comprehensive example can be found in the repository there

You can launch the server from the folder with npm start, and try it with:

curl localhost:3223
curl localhost:3223\?error=handler
curl localhost:3223\?error=implicit
curl localhost:3223\?error=explicit

Related projects

You might also be interested in these projects:

  • express-async-handler: Simple middleware for handling exceptions inside of async express routes.
  • async-middleware: Wrap an asynchronous middleware (or handler) function for Express, Connect, router, etc.
0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago