7. Connecting the dots in server-land
2m

We've got our resolvers and data source ready, but they don't know yet how to work together.

Apollo Server is where all the elements we've built previously (the schema, the resolvers, and the data sources) come together in perfect coordination.

Hand-drawn illustration depicting a GraphQL server juggling 3 components: the schema, resolver function and data sources

In server/src/index.js, where we configured our Apollo Server in Part 1, we can now replace our mocks with resolvers.

Let's remove the mocks object, as well as the mocks property in the ApolloServer constructor. We can also remove the MockList import at the top of the file, because we're not using it anymore.

Next, let's import our resolvers file at the top.

const resolvers = require('./resolvers');

And then add it to the ApolloServer options.

const server = new ApolloServer({
typeDefs,
resolvers
});
1
2
3
4

That's the resolvers taken care of.

Next, just below our resolvers import, we'll require track-api, our data source file (extending RESTDataSource), and call it TrackAPI (note the PascalCase convention, as we're dealing with the class here).

const TrackAPI = require('./datasources/track-api');

To connect our server with our TrackAPI, we'll add the dataSources key. This is what enables us to access the dataSources.trackAPI (and its methods) from the context parameter of our resolvers. Apollo Server takes care of all the plumbing for us, pretty neat!

To learn more about the options that ApolloServer can receive, check out the documentation.

This is what our server configuration will look like when it's finished:

const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
trackAPI: new TrackAPI()
};
}
});
1
2
3
4
5
6
7
8
9

Code Challenge!

Configure the ApolloServer options with the dataSources key for a RestDataSource Class named SpaceCatsAPI, that we need to access at dataSources.spaceCatsAPI from our resolver. (Watch out, this is case sensitive!)

Why do we need to configure the dataSources key in ApolloServer options?

Our server is now fully configured to work with live data.

Previous
Next