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