11. Code-Along: Connecting resolvers & data sources
2m

General process for writing resolvers

  1. Figure out which endpoint from the REST API gives us the data we need.
  2. Update our RESTDataSource class to include a method that calls that endpoint (if needed).
  3. Use the new data source method in our resolver function to return the correct data for that field.

Resolver parameters

A resolver's function signature can include four positional parameters:

  • parent: The return value of this field's parent field (the previous resolver in the resolver chain)
  • args: Contains arguments passed into this field by clients
  • context: An object shared across all resolvers executing for a particular operation. Typically contains data sources, authorization details, etc.
  • info: Information about the operation's execution state. (We won't need this one.)
Hand-drawn illustration depicting a resolver function signature with its four parameters

Goal

Resolve the fields for our test query using real data from the Catstronauts REST API.

query Query {
tracksForHome {
id
}
}

Code-Along

Step 1: Figure out which REST endpoint gives us the data we need

We know we want tracksForHome to return a list of Track objects. Look through the Swagger docs for the Catstronauts API. Which endpoint returns the data we're looking for?

  • Catstronauts REST API

Step 2: Update our RESTDataSource to call that endpoint

Add a method to the CatstronautsAPI class that calls the /tracks endpoint.

src/datasources/catstronauts-api.js
const {RESTDataSource} = require('apollo-datasource-rest');
class CatstronautsAPI extends RESTDataSource {
constructor() {
super();
// the Catstronauts catalog is hosted on this server
this.baseURL = 'https://odyssey-lift-off-rest-api.herokuapp.com/';
}
getAllTracks() {
return this.get('tracks');
}
}
module.exports = CatstronautsAPI;

Step 3: Use the new data source method in our resolver function

Update the resolver function signature to include the context parameter, then use the context to call the new method we added to the data source:

src/resolvers.js
tracksForHome: (_, __, context) => {
return context.dataSources.catstronautsAPI.getAllTracks();
};

Tip: You can use JavaScript destructuring to simplify this resolver by pulling the dataSources object directly out of the context parameter:

src/resolvers.js
tracksForHome: (_, __, {dataSources}) => {
return dataSources.catstronautsAPI.getAllTracks();
};

Checking our work in Sandbox

Run the test query again in Sandbox. Verify that you get back actual track id values (like "c_0") instead of our hard-coded data.

query Query {
tracksForHome {
id
}
}

Task!

Congratulations, you just wrote your first resolver!

Previous
Next