10. Code-Along: Resolver map
2m

Progress check-in

We've got a data source that's connected to our Catstronauts REST API. In Sandbox, try running the test query below:

query Query {
tracksForHome {
id
}
}

We get back an error! "Cannot return null for non-nullable field Query.tracksForHome."

Translation: Our server is returning null for the tracksForHome field. But in our schema, we defined the type of tracksForHome as [Track!]! (and the ! at the end means it can't be null).

Why is our server returning null? Because we don't have a resolver set up for tracksForHome yet. Let's work on that.

Goal

Write the tracksForHome resolver so that we can successfully get back data for the operation below:

query Query {
tracksForHome {
id
}
}

The plan

Create a resolver map in our resolvers.js file.

A resolver map is an object that contains all the resolver functions for your server.

  • The resolver map has top-level fields that correspond to your schema's types (like Query or Movie in the example below).
  • Within a type, there are additional properties for each field and its corresponding resolver function.
  • Each resolver function's name should match the name of the field it populates.

Example resolver map:

const resolvers = {
Query: {
movie: () => {
/* ... */
}
},
Movie: {
title: () => {
/* ... */
},
cast: () => {
/* ... */
}
}
};

Code-Along

  1. Create a resolver map in the src/resolvers.js file. Let's start with the Query.tracksForHome field. Our schema tells us that the tracksForHome field has a type of [Track!]!, so its resolver needs to return an array of Track objects. For now, let's hard-code a return value with a fake track id:
src/resolvers.js
export const resolvers = {
Query: {
tracksForHome: () => {
return [
{
id: 5
}
];
}
}
};
  1. Now import the resolver map into server index.js, and pass it into your ApolloServer instance:
src/index.js
// ... imports
import {CatsAPI} from './datasources/cats-api.js';
import {resolvers} from './resolvers.js';
const typeDefs = gql(readFileSync('./src/schema.graphql', {encoding: 'utf-8'}));
const server = new ApolloServer({
typeDefs,
resolvers
});
// ...
  1. Run the query in Sandbox and verify that you get back your hard-coded value for the track's id.
query Query {
tracksForHome {
id
}
}

Expected response:

{
"data": {
"tracksForHome": [
{
"id": "5"
}
]
}
}
Previous
Next