Gepost op vrijdag 26 april 2019 om 12:04u.

Techtip: How (Apollo) Graphql changed my life

Introduction

My name is Jens, I’m a full-stack JavaScript developer at Codious
and I focus on React and Node as main tech stack.

Like in most React projects, my code evolved to where I
needed something to manage and store my data on the front-end. Also, like most
React developers, I choose redux as the main technology to do this.

I first started with the official redux tutorial and docs,
watched some video’s on YouTube and did some POC’s with it.

This is pretty neat I thought to myself, and started using redux in my next React projects.
The more I worked with it though, the more it annoyed me. All the boiler plate code, changing the reducers every time I had a new state related field, making sure that all the data was normalized before it got in my store, … I’m pretty sure, all of you will recognize these issues and maybe even acted the way I did: I started doing some extra research on redux.

The research

I started searching on forums (stackoverflow.com, reddit.com, etc.) and reading articles (medium.com, hackernoon.com, etc.) and searched pretty much in this order:

Question Answers
What can I do to make it easier/less tedious? Install library x or y OR DON’T USE REDUX
Do I need Redux? For what you’re doing: probably not
What are the alternatives? Mobx, Graphql, ..

After that, I must admit that I still kept using redux for a
few months because I was the one that introduced it in the client’s projects at
that time and was kind of ashamed to admit that it might not have been the best
choice.

Around that time, a new colleague (also a consultant but
from another company) arrived at that client, and he had a lot more experience
than me. I got a new project with the client and he told me: ‘hey man, let’s
not use redux this time, some colleague of my consultancy company contributed
to this thing called Apollo and it is awesome’.

It seems the Tech-gods gave me another chance…

Starting Apollo Graphql

So here I was (after defending to business that is was a
good idea to introduce a new technology that none of us had ever used), given a
blank canvas to start my Apollo Graphql journey.

I’m not going to lie, it was really hard to start with
something without knowing anything about it, without people to ask questions to
and that was so different from what I was used to (being redux).

But I have ZERO regrets!

After understanding the basics, it started to feel more
natural and more intuitive than redux ever had. Graphql makes your life easier
by:

Are you excited yet?

Let’s get technical

What actually is this Graphql you speak of?

In short: a query language for your API

A more detailed explanation:

Graphql is a layer between the sender and the receiver of API requests.
With Graphql you only receive the data you need, nothing more nothing less.
In case you have multiple data sources, Graphql can easily combine these sources without you having to change your api’s.

How does Graphql work?

Graphql server
The Graphql server consists of typedefs and resolvers.
Typedefs are a schema of the types that you’ll be using in your app.

E.g.:

type Name {
  firstName: String
  lastName: String
}

In this example you can see:

A custom type Name that has 2 ‘properties’ of the type String.
String is one of the built-in scalar types (others are: Int, Float, Boolean and ID).

There is also the Query type and the Mutation type.
Query is used to get data, mutations are mostly used to save/update data.

Resolvers are the
handlers of the types (mostly of the Queries and Mutations).

E.g.:

{
  Query: {
    appUsers: () => userApi.getUsers(),
  }
  Mutation: {
    addUser(root, { newUser } ) => return userApi.add(newUser),
  }
}

In this example you have a Query type ‘appUsers’ that is
resolved by calling the getUsers function from the userAPI and a ‘addUser’
mutation that accepts a newUser variable to add a user.

Graphql client

The Graphql client sends queries or mutations to the Graphql
server and uses types to get data with a specific structure.

You can use Graphql without a library, but I would recommend
using a library as it handles the less fun parts for you.

An example of a Graphql client query using Apollo:

import gql from "graphql-tag"; 
import client from ‘../client’;
const userId = 0;
const GET_APP_USERS = gql`
  query AppUsers($userId: Int){
    appUsers(userId: $userId) {
      id
     email
    }
  }
`;
const {data, loading, error} = await client.query({ query: GET_APP_USERS , variables: { userId } })
console.log(data.user);

In this example we call the appUsers query, give it the userId variable and tell it to only return the id and the email address of the user.
In human language this would be: get me the id and email for the user with user id x.
One of the perks of Apollo is that it tells you what the current state of your query is (in the example: { data, loading or error }).

Apollo you say?

Apollo is a JS library for both the Graphql server and the
Graphql client.

You are not required to use them together, so if for
instance you have a .net backend, you can use a .net Graphql server library and
still be able to use the react/vue/angular Apollo client.

Advantages of Apollo Graphql client

  1. Declarative data fetching: all logic to fetch data
  2. All of the logic for retrieving your data, tracking loading
    an error states and updating your UI is encapsulated in a single component
  3. Zero config caching
  4. Caching is an out of the box feature, that is easy to use
  5. Vibrant ecosystem
  6. A lot of settings are configured by default, this is especially
    useful if you’re new to Graphql. When time comes for more advanced use, you can
    still change the config manually.
  7. The client is available for 3 major javascript frameworks
    1. React
    1. Angular
    1. Vue

Advantages of Apollo Graphql server

  1. Easy start
  2.  it takes less than 2
    minutes to create a new Graphql server with Apollo.
  3. Incremental adoption
  4. You can go very advanced, but you don’t have to do it all at
    once.
  5. Universal compatibility
  6. It is compatible with all kinds of data sources and even has
    an awesome class called `dataSources`, which has server side caching and very
    clean http handling.
  7. It is compatible with any other Graphql client.
  8. Production readiness
  9. There is no fundamental difference between a production
    build or a development build

 

My final 2 cents

I’m in love with Apollo Graphql.
There I said it!

Graphql really made my data handling easier and Apollo played a big part in that.
We were able to rebuild the whole app in 3 weeks vs 3 months the first time.
There still are small things that need to be improved in Apollo, but all in all, it’s a really solid Graphql library for both server and client.

If you need more info about Graphql or Apollo, check these
links out:

https://graphql.org/
https://www.apollographql.com/

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *