我想使用fastify-http-代理插件和fastify-3.x。
然而,当我尝试在我的应用程序中使用它时,我会遇到一些困难。
让我解释一下我的要求:
在我的应用程序中,用户将被呈现一组环境。当用户选择特定环境(例如env-1)时,我需要对另一个服务进行REST调用,传递env-1 ID以获取我的上游的IP地址和该上游的授权令牌(基本用户名:密码)。
当用户选择另一个环境(比如env-2)时,我应该根据env-2“重新设置”新的上游授权令牌和新的授权令牌。
为此,我想动态地注册上游和auth令牌。我看到了fastify-http-代理测试案例的例子。然而,所有的例子都只是在replyOptions步骤中添加server.register(proxy, ...)。
我明白我需要覆盖getUpstream和rewriteRequestHeader。但是,由于无法理解如何将其推迟到基于环境选择的后期阶段,可以通过调用不同服务的API来编写逻辑以获取上游端点IP地址和上游授权信息。
同时,如果我想记录一些信息(比如说一些遥测信息) ..将请求代理到上游服务器需要多长时间),最好的方法是什么。
只是为了在代码片段中演示它:
const server = Fastify()
server.register(proxy, {
upstream: '',
replyOptions: {
getUpstream: function (original, base) {
// Here I want to pass the selected environment ID
// Based on the environment ID, will make other services' API call to get the upstream
return `<...>`
}
rewriteRequestHeaders: (originalRequest, headers) => {
// Here I want to pass the selected environment ID
// Based on the environment ID, will make other services' API call to get the envAuth
return {
...headers,
"Authorization": envAuth
};
}
}
})发布于 2022-01-29 08:06:45
getUpstream和rewriteRequestHeaders参数是同步函数,因此不能执行异步操作,例如HTTP。
这样做的一个选择是可以在这些参数中使用本地缓存。
伪码:
const cache = {}
server.post('/select-env', async (request, reply) => {
const data = await datasource.load(request.userId, request.body.env)
cache[request.userId] = { data }
return 'loaded'
})
server.register(proxy, {
upstream: '',
replyOptions: {
getUpstream: function (original, base) {
const userId = original.headers['user-id']
return cache[userId].data.upstream
},
rewriteRequestHeaders: (originalRequest, headers) => {
// Here I want to pass the selected environment ID
// Based on the environment ID, will make other services' API call to get the envAuth
const userId = originalRequest.headers['user-id']
return {
...headers,
Authorization: cache[userId].data.auth,
}
},
},
})其他备选办法是:
Request参数访问Fastify的origin对象。您也可以通过向模块添加此功能来访问它。https://stackoverflow.com/questions/70895874
复制相似问题