Tutorial

Introduction to Apollo Boost

GraphQL

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

With as much as we’ve gone over creating APIs with GraphQL and Prisma in previous articles, we’ve never actually applied our custom backend to a client-side app. In this article, you’ll learn how to let your user interact with your backend through queries and mutations using Apollo Boost, a package that gives us everything out of the box to use the Apollo Client.

Installation

I’m going to try to take a more general approach and use Apollo without any other libraries like React or Vue. So we’re just going to need an HTML and JavaScript file with the parcel bundler to let us use the latest JavaScript features without fumbling around with webpack. Throwing in babel-polyfill will give us access to async/await.

$ npm install parcel-bundler apollo-boost graphql babel-polyfill

Backend Setup

To avoid focusing too much on the backend I’ve made this starter with a few resolvers for you to work with. You’ll need a Heroku account with a Postgres database setup, which you can read up on here, and add the credentials to an env file.

Just remember to run this and start your project in a separate terminal.

$ cd prisma
$ docker-compose up -d 
$ prisma deploy 
$ cd ../
$ yarn get-schema 
$ yarn start

Or if you don’t want to fumble around with a custom backend, I recommend checking out GraphCMS and creating a post model to play with.

Queries

Connecting to our backend couldn’t be simpler, just toss in our URI to ApolloBoost and you’ll be all hooked up. If you’ve ever worked with Gatsby before, you’re should already be very familiar with the gql tag function. With gql and some backtics we can structure our requests exactly how we would in GraphQL Playground.

Now our server’s query method will take our request and return a promise. Pushing everything into a div will do for rendering. Keep in mind that this is still all front-end code, so we access DOM elements directly.

index.js
import "babel-polyfill";
import ApolloBoost, { gql } from 'apollo-boost';

const server = new ApolloBoost({
  uri: 'http://localhost:4000/' // Or to you GraphCMS API
});

const query = gql`
  query {    
    posts {
      title 
      body
    }
  }
`;

const render = posts => {
  let html = '';

  posts.data.posts.forEach(post => {
    html += `
      <div>
      <h3>${post.title}</h3>
      <p>${post.body}</p>
      </div>
    `;
  });
  document.querySelector('#posts').innerHTML = html;
};

const getPosts = async query => {
  const server = new ApolloBoost({ uri: 'http://localhost:4000/' });

  const posts = await server.query({ query });
  render(posts);
};

getPosts(query);
index.html
<body>
  <div id="posts"></div>
</body>

Mutations

Mutations are just as easy as you would imagine, just make your mutation as you normally would and pass it to the server’s mutate method. We can even submit data with our form without setting up a standard server, since this is all client-side already.

index.html
<body>
  <form id="form">
    <input type="text" name="title" placeholder="Title" />
    <input type="text" name="body" placeholder="Body" >
    <div class="controls">
      <button type="submit" id="submit">Submit</button>
      <button type="button" id="clearPosts">Clear All</button>
    </div>
    </form>

  <div id="posts"></div>
</body>
index.js
const addPost = async data => {
  const mutation = gql`
    mutation {
      addPost(data: {
        title: "${data.title}",
        body: "${data.body}"
      }) {
        title
      }
    }
  `;

  await server.mutate({ mutation });
  getPosts(query);
};

const submit = document.querySelector('#submit');
const form = document.querySelector('#form');

submit.addEventListener('click', e => {
  e.preventDefault()

  addPost({
    title: form.elements.title.value,
    body: form.elements.body.value
  })

  form.reset()
});
const clearAll = async () => {
  const mutation = gql`
  mutation {
    clearPosts {
      count
    }
  }`;

  const count = await server.mutate({ mutation });
  console.log(`${count.data.clearPosts.count} item removed`);
  getPosts(query);
};

const clearBtn = document.querySelector('#clearPosts');
clearBtn.addEventListener('click', () => clearAll());

Closing Thoughts

Sadly, Apollo Boost really doesn’t help us much with subscriptions, which turns out to be a significantly more complicated process. But overall, Apollo Client makes messing around with fetch requests seem like working with smoke signals 🔥.

0 Comments

Creative Commons License