Skip to content

Allows fastify-like use of async functions as Express router handlers

Notifications You must be signed in to change notification settings

lynxtaa/express-better-async-wrap

Repository files navigation

Express Better Async Wrap

CI/CD npm version Codecov

Allows fastify-like usage of async functions as Express router handlers.

Unlike express-async-wrap it calls response.send with returned data automatically.

Install

npm install express-better-async-wrap --save

Usage

Wrapping async route handler

const { wrap } = require('express-better-async-wrap')

app.get(
  '/data',
  wrap(async (req, res) => {
    const data = await getDataSomehow()
    return data
  }),
)

Warning: You can't return undefined, otherwise res.send won't be called

Responding inside route handler

const { wrap } = require('express-better-async-wrap')

app.get(
  '/file',
  wrap(async (req, res) => {
    await writeFile(path)
    res.sendFile(path)
  }),
)

Warning: If you are responding inside route handler, you must return undefined

Wrapping error handler middleware

const { wrapError } = require('express-better-async-wrap')

app.use(
  wrapError(async (err, req, res, next) => {
    await doSomethingAsync()
    res.status(500).send('Something broke!')
  }),
)

Usage with Typescript

import { wrap } from 'express-better-async-wrap'

app.put(
  '/user/:id',
  wrap<{
    Params: { id: string }
    Querystring: { throwIfNotFound?: string }
    Body: { name: string; age: number }
    ResBody: { user: User | null }
  }>(async (req, res) => {
    const user = await User.findOne(req.params.id)

    if (!user) {
      if (req.query.throwIfNotFound) {
        throw new Error('User not found')
      } else {
        return { user: null }
      }
    }

    await user.update({ name: req.body.name, age: req.body.age })

    return { user }
  }),
)

About

Allows fastify-like use of async functions as Express router handlers

Resources

Stars

Watchers

Forks

Packages

No packages published