这个在 express 中接受 RequestHandler 的函数是如何工作的?

How does this function that takes in a RequestHandler in express work?

我在 GitHub 上浏览了 Express 服务器的一些代码示例,发现了这个用于环绕 REST API 控制器的函数,我很困惑它是如何工作的...

import { RequestHandler } from 'express';

export const catchErrors = (requestHandler: RequestHandler): RequestHandler => {
  return async (req, res, next): Promise<any> => {
    try {
      console.log(req.body) **// returns requestHandler's req parameter //**

      return await requestHandler(req, res, next);
    } catch (error) {
      next(error);
    }
  };
};

它用于环绕 REST API 控制器以捕获错误并将其传递到错误处理中间件。这种用法的一个简短示例是:

import {catchErrors} from './error'
export const fetchData = catchErrors(async (req: Request, res: Response) => {
  /// perform data fetching here ///
  return res.status(200).send()

})

我对 catchErrors 函数的工作原理感到困惑。据我了解,requestHandler 参数指的是原始 REST 控制器回调。但是, catchError 的下一部分说 return async (req, res, next): Promise<any> => {...} 这个 (req, res, next) 从哪里来?我尝试控制台记录 req.body 结果是上面解析的 requestHandler 参数的请求体。我不明白如何以这种方式引用 requestHandler 的 (req, res, next) 而不是说 requestHandler.req(这不起作用)?

GitHub link 我在哪里找到这段代码:https://github.com/oldboyxx/jira_clone/blob/master/api/src/errors/asyncCatch.ts

catchErrors 只是 return 中间件功能的辅助功能,来自另一个中间件功能,增强或添加功能。在您的情况下,将 fetchData 视为

 async (req, res, next): Promise<any> => {
    try {
      console.log(req.body) **// returns requestHandler's req parameter //**

      const fetchFunction = async (req: Request, res: Response) => {
           /// perform data fetching here ///
           return res.status(200).send()

      }
      return await fetchFunction(req, res, next);
    } catch (error) {
      next(error);
    }
  };


这是一个有效的 express 中间件。看看 higher order function, decorator pattern and closures 是同一个概念。