GraphQL

What, Why and How.

@peterpeerdeman

πŸΌπŸ’©πŸ’€πŸ˜…

"building our API's with GraphQL has been awesome"

TopTaal
(language course planning and finance)

Ministry of Defence
(vehicle maintenance app)

Ruler
(compliance control SaaS)


History.

History

  • 2013 - Lifely Founded
  • 2014 - NodeJS
  • 2015 - Meteor
  • 2015 - Meteor & GraphQL
  • 2015 - Meteor Apollo & GraphQL
  • 2016 - NodeJS, Apollo & GraphQL
  • 2020 - NodeJS, Apollo & GraphQL

Why.

"Back in the day, we wanted to be as RESTful as possible"

REST has problems

nested data

image from https://medium.com/@sagish/node-with-benefits-using-coffeescript-in-your-stack-e9754bf58668

mysterious query parameters

                            
GET /api/dashboard?
courseData=true&
lastEnrolled=true&
duePayments=true&
filter=mobile&
randomundocumentedparam[0]=surewhatever
                            
                        

random responseformat

                            
GET /v1/dashboard/default/Loadtasks?mode=&day=&pageload=true
                            
                            
<div class="dossier_item " data-index="3" dossierid="2770" data-requesthash="3ec0e17ca850b9e9b59869921939daaf">
<div class="clear"></div>
<div id="dossierview" class="allmywrf" divtype="dossierview">
<div class="dossier_left" >
<input type="hidden" value="1" name="allowscrollallmywrf" id="allowscrollallmywrf" /><div class="dossier_item " data-index="0" 
dossierid="2176" data-requesthash="3c2f07c3743095676393a862c8ed903a">
<div class="avatar_wrapper" style="width:130px;min-width:130px;">
<div style="font-size:1.2em;"><span style="color:rgba(232, 75, 61, 1);white-space:nowrap;"><span class="icon-alarmclock" style="margin-right:10px;"></span>12-08-2019</span></div></div>
<div class="dossier_item_content"> <div class="dossier_item_description"> <div class="dossier_title">
                            
                        

entityless methods with sideeffects

                            
POST /api/v1/somerandomrpccall/pleasedontsuemefornotadheringtorestspec
                            
                        

versioning & legacy support


POST /api/v1/user/


POST /api/v2/user/sureillkeepthoseworking


POST /api/v3/user/pleasedontmakeme-remaplegacyfields-again


POST /api/v4/user/yeahsureilldoitagain
                            
                        

documentation? (swagger was ok)

  • versioning

What.

GraphQL?

"Query language
for API's"

oh wow, there is even an animation showing off versioning

🀯

Good standards need good tools

Introducing GraphiQL

graphiql (graphql exploration tool)

Any frontend can write its own query
for exactly the data they need from the API

graphql query vanilla javascript

                        
var query = `query _($searchText: String) {
  courseMaterials(searchText: $searchText)  {
    _id
    name
  }
}`;


fetch(β€˜/api/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },  
  body: JSON.stringify({
    query,
    variables: { searchText },
  })
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
                        
                    

declarative data fetching (apollo & react)

                        
import gql from "graphql-tag";
import { Query } from "react-apollo";

const GET_COURSEMATERIALS_QUERY = gql`
    query _($searchText: String) {
        courseMaterials (searchText: $searchText) {
            _id
            name
        }
    }
` 

const CourseMaterialsContainerComponent = () => (
  <Query query={GET_COURSEMATERIALS_QUERY}>


    {({ loading, error, data }) => {
      if (error) return <Error />
      if (loading) return <Loading />;

      return <CourseMaterialList coursematerials={data.coursematerials} />
    }}
  </Query>
)

                    

"Thats great, now show me something fancier"

Apollo advanced

  • fetchMore() - superclean pagination API
  • prefetching - already retrieve next data on hover
  • InMemoryNormalizedCache - Zero-config caching
  • optimisticResponse - simulate the results of a mutation
  • subscriptions - push data from the server to the clients

graphql subscriptions

an API standard for websocket-style communication

https://medium.com/@tfarguts/websockets-for-beginners-part-2-9a1970a1c228

graphql subscriptions

                        
subscription onCommentAdded($repoFullName: String!){
  commentAdded(repoFullName: $repoFullName){
    id
    content
  }
}


{
  "data": {
    "commentAdded": {
      "id": "123",
      "content": "Hello!"
    }
  }
}

                

subscriptions in react



const COMMENTS_SUBSCRIPTION = gql`
  subscription onCommentAdded($repoFullName: String!) {
    commentAdded(repoFullName: $repoFullName) {
      id
      content
    }
  }
`;


function DontReadTheComments({ repoFullName }) {
  const { data: { commentAdded }, loading } = useSubscription(
    COMMENTS_SUBSCRIPTION,
    { variables: { repoFullName } }
  );
  return <h4>New comment: {!loading && commentAdded.content}</h4>;
}
                    
                

How.

GraphQL ...

As Integration Layer

HvA Student App

integrating both direct database and legacy REST calls

GraphQL ...

as micro-API for
existing SSR app

Yearn Recruitment

Legacy Python app with GraphQL layer replicating legacy pages

"But what about big corporate environments?"

KLM case

"Large Scale Web Apps on GraphQL"

https://www.youtube.com/watch?v=T2njjXHdKqw

KLM GraphQL architecture

GraphQL at KLM

  • 4 services, 4 servers, 4 GraphQL API's
  • independant service scaling
  • ensures you get only the data you need
  • reduces network traffic
  • shared types published as npm packages

GraphQL & SFCommerceCloud

Demo

Lifely ❀️ GraphQL for...

  • uniformity
  • linked data hydration done right
  • strong typing == expectation management
  • auto documented API
  • versioning flexibility
  • consolidating microservices / legacy into 1 API
  • but most of all...

frontend backend ❀️

frontend backend ❀️

  • API clarity: if it's there, it works like this
  • documentation and handover
  • frontend involvement in discussing API / contracts

Want to get started?

  • howtographql.com tutorial by Prisma
  • advancedreact.com course by Wes Bos

Lifely would love to help you out!

GraphQL

What, Why and How.

@peterpeerdeman
peter@lifely.nl

What about
manipulating data?

graphql mutation

GraphQL "FAQ" "FPP"

Frequently Posed Problems

"We don't use Javascript on our backend"

No Javascript?

GraphQL packages for NodeJS, C#, Java, Python, PHP

"You don't get any decent caching do you?"

No Caching?

You lose HTTP caching but can still cache data inside the API layer

"Querying fields from frontend doesn't sound secure"

Security?

Every field has a resolve method and can be guarded as you would guard a REST endpoint