Introduction to GraphQL, Apollo + Angular

Sylwia Laskowska

 

Facebook

GraphQL was developed internally by Facebook in 2012 before being publicly released in 2015.

GraphQL was released as a specification.

  GraphQL is a query language that provides a common interface between the server and the client for fetching and manipulating data

REST

Multiple endpoints

 

/users

/users/<id>

/addUser

/editUser/<id>

/deleteUser/<id>

 ...

GraphQL

 

                        /api

Build a schema

Schema Definition Language (SDL)

type User {
    id: ID!
    name: String!
    age: Int
    friends: [Friend!]!
}

A GraphQL schema is at the center of any GraphQL server implementation and describes te functionality available to the clients which connect to it. The core building block within a schema is the Type.

Queries

Every GraphQL service has a query type

type Query {
    users: [User]
    user(id: ID!): User
}
query {
    users {
        id
        name
    }
    user(id: "1234") {
        id
        name
        friends {
            name
        }
    }
}

Sample schema

Sample query

The most powerful feature of GraphQL

Mutations

Make changes on your server

type Mutation {
    addUser(name: String!, description: String!): User
    editUser(id: ID!, description: String): User
}
mutation {
    editUser(id: "1234", description: "Some desc") {
        id
        name
    }
}

Sample schema

Sample mutation

Apollo Client

Simply to get started with

Small and flexible

Incrementally adaptable

Caching, optimistic UI, subscriptions support and more

Getting started

Installation with Angular Schematics:

ng add apollo-angular

Installation without Angular Schematics:

apollo-client

apollo-angular

apollo-cache-inmemory

apollo-link

apollo-angular-link-http

graphql

graphql-tag

Basic query

import gql from 'graphql-tag';

export const SINGLE_CAT_QUERY = gql`
  query GetOneCat($catId: ID!) {
    cat(id: $catId) {
      id
      name
      description
      photoUrl
      color
      likes
    }
  }
`;
this.apollo.watchQuery({
    query: SINGLE_CAT_QUERY,
    variables: {
        catId: id
    }
}).valueChanges.subscribe(({ data }) => {
    this.cat = data.cat;
});

Basic mutation

import gql from 'graphql-tag';

export const ADD_CAT_MUTATION = gql`
  mutation AddNewCat($name: String!) {
    addCat(name: $name) {
      id
      name
    }
  }
`;
this.apollo.mutate({
    mutation: ADD_CAT_MUTATION,
    variables: {
        name: catFormValue.name
    }
}).subscribe();

Optimistic UI

Non-optimistic vs optimistic UI

optimisticResponse: {
    incrementLikes: {
        id: this.cat.id,
        likes: this.cat.likes++,
         __typename: 'Mutation'
    }
}
Credit: Igor Mandrigin

Thank you!

Made with Slides.com