Add asyncController

This commit is contained in:
Maciej Ziarkowski 2019-09-17 18:05:05 +01:00
parent 5995adeb88
commit ef4d46e36b

View File

@ -0,0 +1,17 @@
import { Request, Response, NextFunction } from 'express';
/**
* A wrapper for controller functions that return a Promise, enabling them to be used with Express
* Without this wrapper, Promise rejections caused by an error in the controller will not be passed properly
* to subsequent middleware layers.
* @param fn the async controller function to be wrapped
* @returns controller function which handles async errors correctly
*/
function asyncController(fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
}
export default asyncController;