Skip to content

Instantly share code, notes, and snippets.

@edoves
Created October 30, 2024 14:44
Show Gist options
  • Save edoves/e3fc71086bfdb2f2c334fb62cc3f264d to your computer and use it in GitHub Desktop.
Save edoves/e3fc71086bfdb2f2c334fb62cc3f264d to your computer and use it in GitHub Desktop.
How to use catchAsync with Class conroller in both function declaration and class fields

How to use catchAsync with Class conroller in both function declaration and class fields

catchAsync function

import { NextFunction, Request, Response } from 'express'

type AsyncFunction = (
  req: Request,
  res: Response,
  next: NextFunction
) => Promise<any>

export const catchAsync = (fn: AsyncFunction) => {
  return (req: Request, res: Response, next: NextFunction) => {
    fn(req, res, next).catch(next)
  }
}

<!--version 2  -->
export function asyncMiddleware(handler: AsyncFunction) {
  return async (req: Request, res: Response, next: NextFunction) => {
    try {
      await handler(req, res, next)
    } catch (error) {
      next(error)
    }
  }
}

class field or function expression version

class UserConroller {
   public register = catchAsync(async (req: Request, res: Response) => {
    const { name, email, password } = req.body

    const userExist = await User.findOne({ email })

    if (!name || !email || !password) {
      res.status(400)
      throw new Error('Please include all fields')
    }

    if (userExist) {
      res.status(400)
      throw new Error('User already exists')
    }

    const user = await User.create({
      name,
      email,
      password: hashSync(password, 10),
    })

    if (user) {
      console.log('new user created')
      res.status(201)
      res.json({
        status: 'success',
        data: { _id: user._id, name: user.name, email: user.email },
      })
    }
  })
}

export default new UserConroller()

function declaration version

class UserConroller {
   public registerUser(req: Request, res: Response, next: NextFunction) {
    return catchAsync(async (req: Request, res: Response) => {
      const { name, email, password } = req.body

      const userExist = await User.findOne({ email })

      if (!name || !email || !password) {
        res.status(400)
        throw new Error('Please include all fields')
      }

      if (userExist) {
        res.status(400)
        throw new Error('User already exists')
      }

      const user = await User.create({
        name,
        email,
        password: hashSync(password, 10),
      })

      if (user) {
        console.log('new user created')
        res.status(201)
        res.json({
          status: 'success',
          data: { _id: user._id, name: user.name, email: user.email },
        })
      }
    })(req, res, next)
}

export default new UserConroller()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment