GraphQL, Apollo & Subscriptions.

@peterpeerdeman

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

"create fullstack apps
with our clients"

TopTaal
(course planning and finance)

Defensie
(vehicle maintenance)

Ruler
(compliance control)

Kandidaatvinden
(live jobchat)


History

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

"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

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>;
}
                    
                

peter, get on with the demo already

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

We ❀️ 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

Want to do a project with us?
Get in touch! βœ‰οΈ

GraphQL, Apollo and Subscriptions.

What about
manipulating data?

graphql mutation