【问题标题】:Forward fetch response headers to Apollo graphql response将获取响应标头转发到 Apollo graphql 响应
【发布时间】:2019-07-26 10:32:03
【问题描述】:

我在 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 响应中包含“缓存状态”标头?

【问题讨论】:

  • 你知道如何获取响应头等吗?

标签: express graphql apollo apollo-server


【解决方案1】:

假设您是来自apollo-datasource-restRESTDataSource,您可以覆盖didReceiveResponse 以拦截响应并返回自定义返回值。

这是 Typescript 中的代码 sn-p,如果需要,可以通过删除参数/返回类型和访问修饰符轻松地将其转换为 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;
  }
}

【讨论】:

    【解决方案2】:

    我认为你可以利用 ApolloServerLambda()formatResponse 并以适当的标题响应。我自己没有尝试过。但是看着document我觉得应该有帮助

     formatResponse?: (
        response: GraphQLResponse,
        requestContext: GraphQLRequestContext<TContext>,
      ) => GraphQLResponse | null;

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2020-08-06
      • 2018-05-06
      • 2019-07-26
      • 2019-05-22
      • 2013-10-04
      • 2015-09-17
      • 2022-12-02
      • 2020-01-18
      相关资源
      最近更新 更多