DRY RESTDataSource methods

Hello!

Beginner who has completed the Odyssey GraphQL Tutorials. Apologies if this is a stupid question but how do you avoid repetition when creating the various methods that makeup the class? Example:

export class anAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = “https://api.xyz.com”;
}

getMethodOne(token) {
return this.get(/endpointOne, null, {
headers: { **
** accept: “application/json; charset=UTF-8”,

** authorization: Bearer ${token}**
** },**
});
}

getMethodTwo(id, token) {
return this.get(/endpointTwo/${id}, null, {
headers: {
** accept: “application/json; charset=UTF-8”,**
** authorization: Bearer ${token},**
** },**
});
}

getMethodThree(id, token, fromDate, toDate) {
return this.get(
endpointThree/${id}/transactions?from=${fromDate}&to=${toDate},
null,
{
headers: {
** accept: “application/json; charset=UTF-8”,**
** authorization: Bearer ${token},**
** },**
}
);
}

I’m assuming that this would be achieved using the constructor, but can’t get it to work; I tried

constructor() {
super();
this.baseURL = “https://api.xyz.com”;
this.headers = {
** accept: “application/json; charset=UTF-8”,**
** authorization: Bearer ${token},**
** };**
}

but this didn’t work with the token parameter in the methods.

I am too much of a beginner to determine whether this is a lack of Javascript or Apollo knowledge so apologies if this is not the correct forum. Thank you.

1 Like

We override the willSendRequest method to populated common headers, etc. e.g.

willSendRequest(request) {
    // set API key
    request.headers['X-apikey'] = config.get('api_key');
}

Thank you very much, Aaron - I’ll spend some time investigating that.