From ff25c68112eb4d19f9ac01ad7bebc5b3eaca1816 Mon Sep 17 00:00:00 2001 From: hanoak20 Date: Thu, 4 Jan 2024 00:35:04 +0530 Subject: [PATCH] chore: added a utility function: AsyncRouter. --- src/routes/auth.routes.ts | 3 ++- src/utils/async-router.utils.ts | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 src/utils/async-router.utils.ts diff --git a/src/routes/auth.routes.ts b/src/routes/auth.routes.ts index 413b6563..6bac4b7e 100644 --- a/src/routes/auth.routes.ts +++ b/src/routes/auth.routes.ts @@ -1,10 +1,11 @@ import express from "express"; import { authController } from "../controllers/auth.controller"; import { authenticateUser } from "../middlewares/auth.middleware"; +import { asyncRouter } from "../utils/async-router.utils"; const router = express.Router(); // Login route -router.post("/login", authenticateUser, authController.login); +router.post("/login", authenticateUser, asyncRouter(authController.login)); export default router; diff --git a/src/utils/async-router.utils.ts b/src/utils/async-router.utils.ts new file mode 100644 index 00000000..590d9ed6 --- /dev/null +++ b/src/utils/async-router.utils.ts @@ -0,0 +1,8 @@ +import { Request, Response } from "express"; + +export const asyncRouter = (fn: any) => (req: Request, res: Response) => { + Promise.resolve(fn(req, res)).catch((err) => { + console.error("AsyncRouter Error: ", err); + res.status(500).json({ message: "Internal Server Error" }); + }); +};