代码之家  ›  专栏  ›  技术社区  ›  Curcuma_

提取每次调用的相同方法参数

  •  0
  • Curcuma_  · 技术社区  · 4 年前

    我有一种方法可以帮助响应请求。签字如下:

    function render(req, res, data, kind, route)

    它被多次调用,使用不同的参数。我想要一个更干净的代码

    render(data, kind, route) 知道这一点 req res 调用时,上下文中始终存在。

    如下所示

    router.get('/', async function (req, res, next) {
       // some logic
       // render({}, 'kind', 'route') instead of
       render(req, res, {}, 'kind', 'route')
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Curcuma_    4 年前

    遵循@deceze建议。我最终使用了一个中间件,它附加了一个闭包,如下所示

    const makeRenderer = (req, res, next) => {
      res.locals.renderer = (data, kind, route) => renderer(req, res, data, kind, route)
      next()
    }
    
    
    router.get('/', makeRenderer, async function (req, res, next) {
      const listings = await mongoQueries.getDocumentsSince(
        20, '', req.body.pagination)
      const { page, perPage } = req.body.pagination
      const data = {
        listings: listings.documents,
        addressPoints: [],
        current: page,
        pages: Math.ceil(listings.count / perPage)
      }
      res.locals.renderer(data, 'listings', 'listings')
    })