Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Getting started with Apollo Client and GraphQL

850 views

Published on

Bring GraphQL to applications in an easy way with Apollo Client, one of the most powerful and flexible libraries for consuming GraphQL APIs

Published in: Engineering
  • Be the first to comment

Getting started with Apollo Client and GraphQL

  1. 1. Getting Started with Apollo Client Morgan Dedmon-Wood
  2. 2. $whoami Software Engineer @ Match LinkedIn: morgandedmon.com Github: mrgn-w Twitter: @morgan_dedmon
  3. 3. GraphQL
  4. 4. Apollo Set of tools to use with GraphQL Server Libraries • Apollo-server: bind graphQL endpoint to Node server • Apollo-engine: Middleware for Node • GraphQL-Tools: Build, mock, manipulate, stitch schemas • Subscriptions-transport-ws: transport for Subscriptions
  5. 5. Apollo Set of tools to use with GraphQL Developer Tools • Apollo Dev Tools • Launchpad: Demo platform for GraphQL servers • Apollo-Tracing: Performance Tracing • Eslint-plugin-graphql
  6. 6. Apollo Set of tools to use with GraphQL Client Tools • Apollo Client • View integrations (react-apollo, etc)
  7. 7. Apollo Client Fully featured GraphQL Client • Incrementally Adoptable • Universally Compatible • Simple to get started with • Inspectable and understandable • Community Driven
  8. 8. Framework Agnostic
  9. 9. Fetching Data
  10. 10. Fetching GraphQL Data { "data": { "allPeople": { "people": [ { "name": "Luke Skywalker" }, { "name": "C-3PO" }, { "name": "R2-D2" }, { "name": "Darth Vader" }, { "name": "Leia Organa" } ] } } } query { allPeople { people { name } } }
  11. 11. Fetching GraphQL Data UI Component Query GET JSON
  12. 12. Fetching GraphQL Data { "data": { "allPeople": { "people": [ { "name": "Luke Skywalker" }, { "name": "C-3PO" }, { "name": "R2-D2" }, { "name": "Darth Vader" }, { "name": "Leia Organa" } ] } } } curl -X POST -H "Content-Type: application/json" --data '{ "query": "{ allPeople { people { name } } }" }' https://ourapiurl.com/graphql fetch('https://ourapiurl.com/graphql ', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ allPeople { people { name } } }' }), }) .then(res => res.json()) Plain Fetch
  13. 13. Apollo Fetch UI Component Query GET JSON Bind Data to UI with single function call
  14. 14. Apollo Fetch client.query({ query: gql` query { allPeople { people { name } } } ` })
  15. 15. Apollo Fetch • Batching • Reduced round trips for all data in view • Loading state and network status tracking • Error Handling with error policy options • Refetch • Polling Interval • fetchMore (pagination)
  16. 16. Query Batching • Sending Multiple queries to server in one request • Reduce round trips • Single request means you can utilize Data Loader for batching actual data load from backend DB const client = new ApolloClient({ // ... other options ... shouldBatch: true, });
  17. 17. Data Storage
  18. 18. Caching Graphs Repo Demo-app Name 1 IDStars 30 Usermrgn-w Name ID 30 Repo Collection Repo cool-graph Name 2 IDStars 12 Hierarchy Repositories
  19. 19. Caching Graphs Repo Demo-app Name 1 IDStars 30 Usermrgn-w Name ID 30 Repo Collection Repo cool-graph Name 2 IDStars 12 Hierarchy Repositories
  20. 20. Caching Graphs Repo Demo-app Name 1 IDStars 30 Usermrgn-w Name ID 30 Repo Collection Repo cool-graph Name 2 IDStars 12 Repo Demo-app Name 1 IDStars 30 Repo cool-graph Name 2 IDStars 12 Hierarchy Normalized Repositories User mrgn-w Name ID 30 Repo Collection User:30 Repo:1 Repo:2 Repo:1 Repo:2
  21. 21. Repo:1 Repo:2 Caching Graphs Repo Demo-app Name 1 IDStars 30 Usermrgn-w Name ID 30 Repo Collection Repo cool-graph Name 2 IDStars 12 Hierarchy Normalized Repositories Usermrgn-w Name ID 30 Repo Collection User:30 Repo:1 Repo:2 Repo Demo-app Name 1 IDStars 30 Repo cool-graph Name 2 IDStars 12
  22. 22. Syncing UI State Repo Demo-app Name 1 ID Stars 30 Repo:1 Repo cool-graph Name 2 ID Stars 12 Repo:2User mrgn-w Name ID 30 Repo Collection User:30 Repo:1 Repo:2 UIs are automatically subscribed to observe changes to cached records and will automatically update watchQuery method View Integration {repo: { id: 2, stars: 15 }} 15 Repo:2
  23. 23. Caching Client • Manage data in one place • All queries watch store for changes and update UI accordingly • Keep Data + UI consistent • Avoid unnecessary refetches UI Component UI Component
  24. 24. Utilizing the Cache
  25. 25. Fetch Policies cache-first cache-and-network network-only cache-only
  26. 26. cache-first Tries reading from cache first If all data is there in cache, returns that data Only fetch from network if result is not in cache Query Cache Network Return Data
  27. 27. network-and-cache Tries reading from cache first If the data is in the cache, that data is returned Will always execute query with network interface, regardless of if full data is in cache Query Cache Network Return Data
  28. 28. network-only Never return data from cache Always make a request to the server Query Network Return Data
  29. 29. cache-only Never execute using network interface Always fetch from cache If data does not exist in cache, error is thrown Allows you to only interact with data in your local client cache Query Cache Return Data
  30. 30. Direct Cache Access readQuery writeQuery readFragment writeFragment
  31. 31. Cache Resolvers Map of custom ways to resolve data from other parts of cache Allows us to tell Apollo Client to check the cache for a particular object if that object may have been resolved by another query
  32. 32. Query Minimize Query Send Result Normalize Response Store (InMemory Cache) Compose Results Apollo Client UI Components Update UI Request Data Apollo Client
  33. 33. Further Query Optimization • Batches queries • UI responds to updates to rendered data automatically • Reads from cache where appropriate …But what about what’s left of the query that gets sent?
  34. 34. GraphQL Execution Cycle • Parses query into AST • Validates if query makes sense given the schema • Executes the query
  35. 35. GraphQL Execution Cycle • Parses query into AST • Validates if query makes sense given the schema • Executes the query
  36. 36. • Aggregate query strings at build time • Store Query to DB • Return an ID to reference stored query • Pass ID instead of query
  37. 37. • Mapping between GraphQL Documents and generated IDs • Restricts queries accepted by the server by whitelisting an allowed set • Saves bandwidth between client and server by only sending hash/id instead of full query • Optimizes execution by not having to parse and validate over and over on the server Persisted Queries
  38. 38. • persistgraphql - Build tool • Crawls client code for graphQL documents • Creates mapping and IDs • Writes to JSON file • In Production mode, only the hash is sent • Automatic persisted queries via Apollo Engine • Protocol extension in front of GraphQL server • Sends hash instead of text • Server checks if there is a match in registry • If not found, requests full text from client and saves has to registry for subsequent requests Persisted Queries
  39. 39. Network Stack
  40. 40. Query Minimize Query Send Result Normalize Response Store (InMemory Cache) Compose Results Apollo Client UI Components Update UI Request Data Apollo Client
  41. 41. • “Components” for your data! • Isolate parts of control flow • Composable • Middleware and Afterware Apollo Link
  42. 42. Link Operation Observable • query • Variables • operationName • Extensions • getContext • setContext • toKey
  43. 43. Link Link Link Server Operation Execution Result
  44. 44. • “Components” for your data! • Isolate parts of control flow • Composable • Middleware and Afterware Apollo Link
  45. 45. • Adding Auth headers • Retry failed mutations • Deduping results • Error logging • Deferring expensive query execution • Split execution chain across different protocols Apollo Link Uses
  46. 46. Query Minimize Query Send Result Normalize Response Store (InMemory Cache) Compose Results Apollo Client UI Components Update UI Request Data Apollo Link State! Local Data
  47. 47. Query Minimize Query Send Result Normalize Response Store (InMemory Cache) Compose Results Apollo Client UI Components Update UI Request Data Universal language for data! Local Data REST Apollo Link Rest! (in development)
  48. 48. Apollo Client • Fetch Data • Cache • Syncs client state + server • Query manager • Network Interface • Framework Agnostic • And more! (optimistic UI, SSR, etc)
  49. 49. Why Apollo Client? Do more with less code Reduce complexity Modular Architecture Flexible Universal - Can manage ALL data Highly customizable - No one size fits all, can be crafted to fit your unique needs Excellent tools
  50. 50. Apollo Dev Tools
  51. 51. Apollo Dev Tools
  52. 52. Apollo Dev Tools
  53. 53. Apollo-Boost - Beginner friendly, limited-configuration setup
  54. 54. Match Technology Presents… Kyle Matthews, Creator of Gatsby March 29, 6:30PM @ Match HQ meetup.com/Match-technology-presents
  55. 55. We’re hiring! lifeatmatch.com

×