Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward fetch response headers to Apollo graphql response

I have an apollo-datasource-rest data source setup on an Apollo/Graphql Expressjs server. I'd like to forward a few headers from the fetch response to the /graphql response.

Here is the flow:

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

I see the header in the didReceiveResponse() method of the rest datasource class. I'm not sure this is the right place to access and store it. How do I include the "cache-status" header in the POST /graphql response?

like image 489
chugs Avatar asked Nov 07 '22 20:11

chugs


1 Answers

Assuming you're RESTDataSource from apollo-datasource-rest, you can override the didReceiveResponse to intercept the response and return a custom return value.

Here's a code snippet in Typescript, it can be easily converted to Javascript if need be by removing the parameter/return types and access modifiers.

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;
  }
}
like image 76
Istvan Szasz Avatar answered Nov 16 '22 13:11

Istvan Szasz