How to use catchAsync with Class conroller in both function declaration and class fields
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 ( )