From ef4d46e36b416c4481825140473778d0a4e4b296 Mon Sep 17 00:00:00 2001 From: Maciej Ziarkowski Date: Tue, 17 Sep 2019 18:05:05 +0100 Subject: [PATCH] Add asyncController --- app/src/api/routes/asyncController.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 app/src/api/routes/asyncController.ts diff --git a/app/src/api/routes/asyncController.ts b/app/src/api/routes/asyncController.ts new file mode 100644 index 00000000..333f664b --- /dev/null +++ b/app/src/api/routes/asyncController.ts @@ -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) { + return (req: Request, res: Response, next: NextFunction) => { + Promise.resolve(fn(req, res, next)) + .catch(next); + }; +} + +export default asyncController; \ No newline at end of file