Read header from response with apollo-datasource-rest

Viewed 554
import { RESTDataSource } from 'apollo-datasource-rest';

export class Foo extends RESTDataSource {

    async getFoo(id) {
        const responseFoo = await this.get(`/api/v1/foo/${id}`);
        return FooReducer(responseFoo);
    }
}

Lets say I use this.get go do a GET Request. How can I read the headers in the response? Is this completely missing in the apollo-datasource-rest package?

1 Answers

In the didRecieveResponse method in the RESTDataSource, you can access the response object. Define/override as follows in the RESTDataSource class:

export class Foo extends RESTDataSource {

    async didReceiveResponse(response, request) {
        // use this.authHeader value in the class anywhere
        this.authHeader = response.headers.get('authorization');
    }
    
    async getFoo(id) {
        const responseFoo = await this.get(`/api/v1/foo/${id}`);
        console.log(this.authHeader)
        return FooReducer(responseFoo);
    }
}

The the willSendRequest method (where you can access the req object and set headers etc) runs before firing an http request and didReceiveResponse method is called after receiving a response from an http request.

Related