Apollo + GraphQL + Node.js – how to easily aggregate datasources behind a single GraphQL endpoint

Published on February 21, 2018 by Dave Nicholas

Posted in Technology

TAGGED , , ,

It’s quite common right now to see tweets like “REST = REST IN PEACE” and “GraphQL will do to REST what JSON did to XML”. The reason for this mass approval is that being able to craft data responses whilst writing your front-end code, without having to rewrite your API responses makes your life so much easier. It also reduces the number of requests that you have to make in order to get the data you need.

In this article I want to demonstrate how easy it is to create a multi data source API behind a single GraphQL endpoint using Apollo Server for Node.js.

Apollo server and GraphQL tools make the process of creating a server really easy. They have package implementations for the most popular Node.js servers from Express and AWS Lambda to newer frameworks like Adonis.

Apollo Server requires you to define a GraphQL schema called `typeDefs` and a resolver object called a `resolvers`. The schema describes the structure and the relationships of your data, while the resolver explains how to actually build the data.

This schema defines the relationships between (Red)Rivers, Streams and Brooks, but also defines some queries that we want to be able to run.

Here you can see an example of the above schema in action, running using mocked resolvers.

The resolver defines how the data is bound. It also delegates how defined queries should be handled. The example below demonstrates how we can defer a full text search to different data sources (in this case Algolia). This is a great strategy when you are dealing with relational databases.

You can then combine your `typeDefs` and your `resolvers` using the `makeExecutableSchema` function to return a schema.

const schema = makeExecutableSchema({ typeDefs, resolvers });

Then, use your schema with your framework specific implementation. Below is an example of creating an endpoint using express.js:

app.use(‘/graphql’, bodyParser.json(), graphqlExpress({ schema }));

And there you have it. I hope that the concepts in this article have been useful. You can read more by following this link to a github repo Apollo-express which demonstrates aggregating MongoDB, SQLite, Algolia and Fetch datasources behind a single GraphQL endpoint.