/**
* Wraps an async function to catch any rejections and forward them to the next middleware.
* This allows you to use async/await in route handlers without manually wrapping them in try-catch blocks.
* @category Helpers
* @template R Request type (defaults to Express Request).
* @template S Response type (defaults to Express Response).
* @param {Function} fn The async handler `(req: R, res: S, next: NextFunction) => Promise<void>`.
* @returns {Function} Express-compatible handler `(req: R, res: S, next: NextFunction) => void`.
* @example
* ```typescript
* // Instead of:
* app.get('/users', async (req, res, next) => {
* try {
* const users = await userService.getUsers();
* res.json(users);
* } catch (error) {
* next(error);
* }
* });
*
* // You can do:
* app.get('/users', asyncHandler(async (req, res) => {
* const users = await userService.getUsers();
* res.json(users);
* }));
* ```
*/
export const asyncHandler = (fn) => (req, res, next) => {
// Use void to explicitly ignore the promise return value
// This prevents ESLint warnings about floating promises
void fn(req, res, next).catch(next);
};
Source