发出内部快递请求

时间:2015-01-05 23:19:25

标签: javascript express

我很好奇是否有任何方式在快递中发出内部请求而不经历实际请求的所有实际开销。一个例子可能更好地显示了动机:

app.get("/pages/:page", funciton(req, res)
{
    database_get(req.params.page, function(result)
    {
        // "Page" has an internal data reference, which we want to inline with the actual data:
        request(result.user_href, function(user_response)
        {
            result.user = user.response.json;
            res.send(result);
        });
    });
});

/// ....

app.get("/user/:name", function() ... );

所以我们这里有一条路线,其数据需要另外请求获取更多数据。我想通过像app.go_get(user_href)这样的东西而不是重量级的实际请求来访问它。现在,我已经四处询问,正在采取的策略似乎是“分裂你的逻辑”。但是,它实际上要求我复制逻辑,因为递归数据是通过URL正确引用的(如上例所示)。所以我最终必须自己做路由并在任何地方复制路由。

2 个答案:

答案 0 :(得分:0)

你能避免真实请求的开销吗?不。如果您需要第一个请求中的href来获取用户对象,您绝对需要通过发出第二个“真实请求”来关注该链接。

如果您有一个用户数据库,您可以通过在页面上包含用户ID并进行常规数据库调用而不是关注您自己的href来避免该请求。

关于拆分逻辑的演示重构:

// Keep as little logic as possible in your routes:
app.get('/page/:page', function(req, res){
  var pageId = req.params.page;
  makePage(pageId, function(err, result){
    if(err){ return res.send(500) }
    res.send(result)
  }) 
})

// Abstract anything with a bunch of callback hell:
function makePage(pageId, callback){
  database_get(pageId, function(result) {
    // Since it's only now you know where to get the user info, the second request is acceptable
    // But abstract it:
    getUserByHref(result.user_href, function(err, data){
      if(err){return callback(err)};
      result.user = data.json;
      callback(null, result);
    });
  });
}

// Also abstract anything used more than once:
function getUserByHref(href, callback){
  request(href, function(err, response, body){
    if(response.statusCode != 200){
      return callback(err);
    }
    var user = JSON.parse(body);
    return callback(null, user);
  })
}

// It sounds like you don't have local users
// If you did, you would abstract the database call, and use getUserById
function getUserById(id, callback){
  db.fetch(id, function(err, data){
    return callback(err, data);
  })
}

答案 1 :(得分:0)

我为此uest制作了专用的中间件,请在此处查看我的详细答案:https://stackoverflow.com/a/59514893/133327