我在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()方法中看到了标题。我不确定这是访问和存储它的正确位置。如何在POST / graphql响应中包含“ cache-status”标头?
答案 0 :(得分:0)
假设您是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;
}
}