Intro to GraphQL
(click)

Dara Hayes

dara.hayes@redhat.com

@darahayess

@darahayes

Questions
Definition
far out
It's an alternative way to design APIs... that's all
an alternative to REST APIs, really...
GET http://api.com/users/1
{ name: "Alice", age: 30 }
POST http://api.com/users
{ name: "Bob", age: 50 }
{ result: "success!" }
GET http://api.com/users?age=30
[{ name: "Alice", age: 30 }]
GET http://api.com/users/1
{ name: "Alice", age: 30 }
POST http://api.com/users
{ name: "Bob", age: 50 }
{ result: "success!" }
GET http://api.com/users?age=30
[{ name: "Alice", age: 30 }]
A different way to do the same thing.

Instead of many endpoints like this

GET http://api.com/users/1
POST http://api.com/users

We have one endpoint

http://api.com/graphql
{
  name: "Dara",
  address: "waterford"
}

Example Query

{
  user(id: 1) {
    id
    name
    address
  }
}
{
  "data": {
    "user": {
      "id": 1,
      "name": "Ted",
      "address": "Waterford"
    }
  }
}

Fields are functions

{
  user(id: 1) {
    id
    name
    address
    friends(limit: 3) {
      name
    }
  }
}
{
  "data": {
    "user": {
      "id": 1,
      "name": "Ted",
      "address": "Waterford"
      "friends": [
        {"name": "Bill"},
        {"name": "Alice"},
        {"name": "Jennifer"}
      ]
    }
  }
}

Queries and Mutations

{
  user(id: 1) {
    id
    name
    address
  }
}
{
  addUser(name: "Fred" address: "London") {
    id
    name
    address
  }
}
How does this look on the server?

It all starts with the Schema

type User {
  id: ID
  name: String
  address: String
}

type Query {
  listUsers: [User]
  getUser(id: ID!): User
}

type Mutation {
  addUser(name: String! address: String!): User
}

Background

    🚀   Created by Facebook in 2012

    🎁   Open Sourced in 2015

    📝   It's a specification

    ✅   Available in 13+ languages

    ✨   Reference implementation in Node.js

Let's try to build something

Requirements

    📱  Build a messaging app like Slack

    👨‍👩‍👧‍👦  Users

    ✉️  Messages

    📺  Channels (#random, #javascript, #cats)

    📝  Users send messages to a channel

    ⚡️  Users will receive messages in realtime

The Technology

  • Node.js
  • Apollo Server - a GraphQL Server Framework
  • GraphQL Playground
  • In Memory Database

Tasks

  1. Project Setup
  2. Schema Design
  3. Implement Resolvers
  4. Figure out the Realtime thing
let's get started

GraphQL Subscriptions

type Subscription {
  messageAdded: Message
}
type Subscription {
  messageAddedToChannel(channelId: Int!): Message
}

Clients can subscribe to events over websockets

Pub Sub

S1

S2

Sn

...

LB

demo

Quick Recap

    📝  Schema

    ⚙️  Resolvers

    ⚡️  Subscriptions

✅  You get exactly what you ask for 

✅  Versionless

✅  Schema

❌  Queries can become complex

❌  You need to figure out stuff all over again

🤔  Ecosystem is very JavaScript oriented

One more thing...
done 🍻

Intro to GraphQL in Node

By Dara Hayes

Intro to GraphQL in Node

  • 1,240