我的一位同事帮助我破解了自己的答案。它目前用作特定端点的(快速)中间件GET
,基本上将请求散列到地图中,开始一个新的单独请求。并发的传入请求被散列和检查,并在单独的请求回调上遍历,从而被重用。这也意味着如果第一个响应特别慢,那么所有合并的请求也太慢了。
这似乎比将其破解到 http-proxy-middleware 更容易,但是哦,这完成了工作:)
const axios = require('axios');
const responses = {};
module.exports = (req, res) => {
const queryHash = `${req.path}/${JSON.stringify(req.query)}`;
if (responses[queryHash]) {
console.log('re-using request', queryHash);
responses[queryHash].push(res);
return;
}
console.log('new request', queryHash);
const axiosConfig = {
method: req.method,
url: `[the original backend url]${req.path}`,
params: req.query,
headers: {}
};
if (req.headers.cookie) {
axiosConfig.headers.Cookie = req.headers.cookie;
}
responses[queryHash] = [res];
axios.request(axiosConfig).then((axiosRes) => {
responses[queryHash].forEach((coalescingRequest) => {
coalescingRequest.json(axiosRes.data);
});
responses[queryHash] = undefined;
}).catch((err) => {
responses[queryHash].forEach((coalescingRequest) => {
coalescingRequest.status(500).json(false);
});
responses[queryHash] = undefined;
});
};