0.4.0 • Published 3 years ago

express-better-async-wrap v0.4.0

Weekly downloads
255
License
ISC
Repository
github
Last release
3 years ago

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

3 years ago

0.3.0

4 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago