Using GraphQL with Apollo Client JavaScript SDK

Apollo is a GraphQL client that helps you consume GraphQL APIs.

In this document, we will learn how to use the Apollo client and Contentstack GraphQL queries to power the content of your JavaScript SDK apps.

Prerequisites

Refer the Getting started document for the initial installation procedure. Begin by including packages that are essential for building the Apollo app. Install the following modules using the npm install command:

Refer the Apollo for JavaScript documentation for more details.

Write GraphQL queries

Contentstack provides a GraphQL playground, which is the GraphiQL interface, to test your GraphQL queries in your browser. Use this interface to write and test your queries.

Open a browser of your choice and hit the following URL after filling the required details:

https://www.contentstack.com/docs/apis/graphql-content-delivery-api/explorer/

Note: If you have pieces of data you may want to reuse in multiple places, make use of fragments. Refer the Using fragments doc for more details.

Add modules in server file to invoke Apollo

In order to invoke Apollo as part of the JavaScript, you need to import certain modules to the server file, app.js. Add the apollo-client and apollo-cache-inmemory parameters in the apollo-client instance.

var { ApolloClient } = require('apollo-client');
var { InMemoryCache } = require('apollo-cache-inmemory');
var { HttpLink } = require('apollo-link-http');
var gql = require("graphql-tag");
var fetch = require('node-fetch');

Create a single shared instance of 'Apollo-link' and point it at your GraphQL server. Under the HttpLink module instance, set the URL of GraphQL schema under the uri parameter and use fetch to fetch the data from graphql API.

const cache = new InMemoryCache();
const link = new HttpLink({ uri:'https://graphql.contentstack.com/stacks/<API_KEY>?access_token=<ENVIRONMENT-SPECIFIC_DELIVERY_TOKEN>&environment=<ENVIRONMENT_NAME>',
fetch
})

const client = new ApolloClient({
cache,
link
})

Fetch data using ApolloClient

To fetch all entries of the ‘Product’ content type, add the following code snippet in the server file, app.js.

// ... above is the instantiation of the client object.
client
  .query({
    query: gql`query { all_product{
    items{
    title
    description
  }
  } }`
  })
  .then(result => 
    res.render('./index', result)
    //console.log(result.data.all_product.items)
    )

After executing the above query using the client object of the ApolloClient module, we will fetch the data of specific fields of all entries of the Product content type. You can render the response to view the result.

Example app

We have created an example app that demonstrates the usage of Contentstack GraphQL queries and Apollo JavaScript SDK. Refer this guide and create your own apps easily.

Was this article helpful?
top-arrow