Tutorial

Introduction to Apollo Boost

Updated on April 4, 2022
Default avatar

By Joshua Hall

Introduction to Apollo Boost

This tutorial is out of date and no longer maintained.

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 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 🔥.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Joshua Hall

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel