gpt4 book ai didi

express - 将获取响应 header 转发到 Apollo graphql 响应

转载 作者:行者123 更新时间:2023-12-03 21:04:48 30 4
gpt4 key购买 nike

我在 Apollo/Graphql 上设置了 apollo-datasource-rest 数据源
Expressjs 服务器。我想将一些标题从 fetch 响应转发到/graphql 响应。

这是流程:

POST /graphql

Graphql makes fetch request using this.get('http://example.com/api')
Response from this fetch contains the header "cache-status"

Response from /graphql
I'd like to include the "cache-status" header from the example.com/api response here in the /graphql response

我在其余数据源类的 didReceiveResponse() 方法中看到了 header 。我不确定这是访问和存储它的正确位置。如何在 POST/graphql 响应中包含“cache-status” header ?

最佳答案

假设您是 RESTDataSource来自 apollo-datasource-rest ,您可以覆盖 didReceiveResponse拦截响应并返回自定义返回值。
这是 Typescript 中的代码片段,如果需要,可以通过删除参数/返回类型和访问修饰符轻松将其转换为 Javascript。

class MyRestDataSource extends RESTDataSource {
public constructor(baseUrl: string) {
super();
this.baseURL = baseUrl;
}

public async getSomething(): Promise<any & { headers?: { [key: string]: string } }> {
// make the get request
return this.get('path/to/something');
}

// intercept response after receiving it
protected async didReceiveResponse(response: Response, _request: Request) {

// get the value that is returned by default, by calling didReceiveResponse from the base class
const defaultReturnValue = await super.didReceiveResponse(response, _request);

// check if it makes sense to replace return value for this type of request
if (_request.url.endsWith('path/to/something')) {
// if yes get the headers from response headers and add it to the returned value
return {
...defaultReturnValue,
headers: { headerValue: response.headers.get('header_name') },
};
}

return defaultReturnValue;
}
}

关于express - 将获取响应 header 转发到 Apollo graphql 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994650/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com