express-better-async-wrap
TypeScript icon, indicating that this package has built-in type declarations

0.4.0 • Public • Published

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

Readme

Keywords

Package Sidebar

Install

npm i express-better-async-wrap

Weekly Downloads

1

Version

0.4.0

License

ISC

Unpacked Size

14 kB

Total Files

9

Last publish

Collaborators

  • lynxtaa