Upgrade to Pro — share decks privately, control downloads, hide ads and more …

GraphQL on Rails @ RailsConf 2018

GraphQL on Rails @ RailsConf 2018

Cb09696b034cce3cc79cab80a4bba4a3?s=128

exAspArk

April 17, 2018
Tweet

Transcript

  1. GraphQL on Rails exAspArk Evgeny Li

  2. Hello RailsConf!

  3. Hello RailsConf! https://giphy.com/gifs/car-snow-gx1YKF48aO0ms

  4. None
  5. • Everything you need to know about GraphQL • Simple

    application with Ruby on Rails + React + Webpacker • GraphQL schema definition on the server-side • Consuming GraphQL API, automatic code generation, integration • Extra: error handling, authorization, monitoring, N+1 queries What are we doing today?
  6. Who is using GraphQL? http://graphql.org/users/

  7. But what is GraphQL?

  8. Query Language for APIs http://graphql.org/

  9. Why graph? Query

  10. Why graph? Query Post

  11. Why graph? Query Post Title

  12. Why graph? Query Post Title Content

  13. Why graph? User Query Post Title Content

  14. Why graph? User Query Name Post Title Content

  15. Why graph? User Query Name Post Title Content Comment

  16. Why graph? User Query Name Post Title Content Comment

  17. Why graph? User Query Name Post Title Content Comment Text

  18. Why graph? User Query Name Post Title Content Comment Text

    Mutation Subscription
  19. GraphQL specification http://facebook.github.io/graphql/October2016/

  20. Server describes what data is available User Query Name Post

    Title Content Comment Text Mutation Subscription
  21. Clients ask what data they need User Query Name Post

    Title Content Comment Text Mutation Subscription
  22. TreeQL

  23. Request Response Almost the same shape

  24. • What is GraphQL and why a graph, GraphQL specification

    • New blog application with Rails v5.2 • What is Webpack, Webpacker vs Sprockets • One-way data flow, React vs Turbolinks • Static HTML template Part 1: Bootstrapping simple application
  25. Let’s create a new Rails app https://yarnpkg.com/lang/en/docs/install/

  26. What is Webpack? https://webpack.js.org/

  27. • Hot Module Replacement – faster build time without a

    full reload • Tons of loaders – ES6, CSS post-processors, linters • Tree shaking – exclude unused code • Code splitting – separate static and dynamic parts of your code • Compression, source-maps, minification • WebAssembly support Webpack
  28. Webpack vs Sprockets https://media.giphy.com/media/6Z3D5t31ZdoNW/giphy.gif

  29. • Smooth integration with Webpack – The Rails Way™ •

    React, Angular, Elm and Vue support out-of-the-box • Rails view helpers Webpacker https://github.com/rails/webpacker
  30. Running Webpacker https://github.com/rails/webpacker/issues/1295

  31. Trying to run Webpacker again https://github.com/rails/webpacker/issues/1303

  32. Trying to run Webpacker again https://github.com/rails/webpacker/issues/1303

  33. And again

  34. And again Leaky abstractions

  35. Webpacker Once you become familiar with Webpack, you probably don’t

    need to use Webpacker – an extra dependency, doesn’t support the latest versions. https://medium.com/webpack/webpack-4-released-today-6cdb994702d4
  36. Clone the repo https://github.com/exAspArk/graphql-on-rails

  37. Run Rails

  38. Render layout

  39. Render layout

  40. Render layout

  41. What is React? ____ https://reactjs.org/ • JavaScript library for building

    user interfaces • Update and render just the right components when your data changes • Declarative views make your code more predictable and easier to debug • Encapsulated components that manage their own state • Learn once, write anywhere (React Native), not opinionated • Great ecosystem, a lot of tools and libraries
  42. One-way data flow Browser DOM implementations are generally really slow.

    One-way data-binding is the process of completely regenerating the HTML whenever the state from a single source changes.
  43. Two-way data flow value = ‘Input’ Input

  44. value = ‘Input’ Input value = ‘Input123’ Input123 Two-way data

    flow
  45. Two-way data flow value = ‘Input’ Input value = ‘Input123’

    Input123 value = ‘Input321’ Input321
  46. The jQuery way™ value = ‘Input’ Input value = ‘Input123’

    Input123 value = ‘Input321’ Input321 Source of truth Source of truth
  47. One-way data flow value = ‘Input’ Input value = ‘Input123’

    Input123 Input321 function(‘Input321’) value = ‘Input321’ Input321 Single source of truth
  48. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __
  49. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h?
  50. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h? – Maybe we should upgrade to 1.0.1u first?
  51. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h? – Maybe we should upgrade to 1.0.1u first? – Or can we upgrade to 1.0.2o, right?
  52. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h? – Maybe we should upgrade to 1.0.1u first? – Or can we upgrade to 1.0.2o, right? – Well, it probably depends on our current version version
  53. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h? – Maybe we should upgrade to 1.0.1u first? – Or can we upgrade to 1.0.2o, right? – Well, it probably depends on our current version version – What did we update last time?
  54. Why one-way flow is simpler? Server: – I have OpenSSL

    1.0.1c __ – Can we upgrade to 1.1.0h? – Maybe we should upgrade to 1.0.1u first? – Or can we upgrade to 1.0.2o, right? – Well, it probably depends on our current version version – What did we update last time? Docker: – I have OpenSSL 1.0.1c __ – Can we upgrade to 1.1.0h? – Yes! Simply setup your environment from scratch.
  55. Why one-way flow is simpler? Server: Docker: Init State1 State2

    Init State1 Init State2 No intermediate state
  56. Render React https://reactjs.org/

  57. Render React

  58. Simplify React app

  59. We are a small startup, not Facebook! I used React

    for demonstration purposes only. Yes, using SPA is complicated. But use appropriate tools to solve your problems.
  60. React ___ JS ___ Internet ___ Software ___ World http://www.npmtrends.com/react-vs-@angular/core-vs-vue-vs-ember-source

  61. React routing https://github.com/ReactTraining/react-router

  62. Heaviest objects in the Universe Sun Neutron star Black hole

    node_modules
  63. React routing

  64. React routing

  65. React routing

  66. React routing

  67. Separating React route files

  68. Switching routes

  69. Switching routes

  70. Turbolinks vs React Turbolinks: – Received an event. – Let’s

    re-render the whole page. – Done, just replaced the whole HTML DOM body
  71. Turbolinks vs React Turbolinks: – Received an event. – Let’s

    re-render the whole page. – Done, just replaced the whole HTML DOM body React: – Received an event. – Let’s calculate the final state in Virtual DOM (reconciliation). – Let’s quickly re-render only necessary elements in DOM.
  72. Turbolinks vs React Turbolinks: – Received an event. – Let’s

    re-render the whole page. – Done, just replaced the whole HTML DOM body React: – Received an event. – Let’s calculate the final state in Virtual DOM (reconciliation). – Let’s quickly re-render only necessary elements in DOM. – We could pause until the new data is fetched in 3G (I/O). – We could re-render in smaller chunks during idle time only (CPU)
  73. Adding static HTML

  74. Adding static HTML

  75. • What is GraphQL and why a graph, GraphQL specification

    • New blog application with Rails v5.2 • What is Webpack, Webpacker vs Sprockets • One-way data flow, React vs Turbolinks • Static HTML template Part 1: Bootstrapping simple application
  76. • What is GraphQL and why a graph, GraphQL specification

    • New blog application with Rails v5.2 • What is Webpack, Webpacker vs Sprockets • One-way data flow, React vs Turbolinks • Static HTML template Part 1: Bootstrapping simple application
  77. • GraphiQL – exploring automatically generated documentation • Adding models

    • GraphQL gem v1.8 • GraphQL API endpoint, schema, types, enums, arguments • How GraphQL is different from REST API and what are the benefits Part 2: Describing GraphQL schema
  78. GraphiQL: in-browser IDE https://developer.github.com/v4/explorer/

  79. GraphiQL npm package https://github.com/graphql/graphiql

  80. Installing an npm package

  81. GraphiQL route

  82. New Rails models

  83. Seeds

  84. Preparing DB

  85. GraphQL gem ___ http://graphql-ruby.org/

  86. GraphiQL route

  87. GraphQL schema

  88. GraphQL Post type

  89. GraphQL Types: Active Model Serializer on steroids • Declarative specification

    for available fields • Custom field implementation with Ruby instance methods • Strong type definitions, description for documentation • Type composition (relations) • Don’t worry about response root key names (GraphQL specification) • API consumers specify fields they need
  90. GraphQL Post type

  91. No over-fetching REST: GraphQL:

  92. No over-fetching https://giphy.com/gifs/silicon-valley-3oD3YlNhSe7cqZOV6E

  93. GraphQL User type

  94. GraphQL User type

  95. No under-fetching REST: GraphQL:

  96. GraphQL enums

  97. GraphQL arguments

  98. GraphQL arguments

  99. • GraphiQL – exploring automatically generated documentation • Adding models

    • GraphQL gem v1.8 • GraphQL API endpoint, schema, types, enums arguments • How GraphQL is different from REST API and what are the benefits Part 2: Describing GraphQL schema
  100. • GraphiQL – exploring automatically generated documentation • Adding models

    • GraphQL gem v1.8 • GraphQL API endpoint, schema, types, enums arguments • How GraphQL is different from REST API and what are the benefits Part 2: Describing GraphQL schema
  101. • GraphQL clients • Consuming GraphQL API with modern JavaScript

    tools • Client-side code generation • Seemless integration – contract testing Part 3: Consuming GraphQL
  102. Why use GraphQL clients? • Data fetching • Managing state

    and caching data (Redux is not required) • UI framework integrations (React, Angular, Vue) • Managing websocket connections for GraphQL subscriptions • Query batching • Helpers for pagination • Dev tools for debugging and introspecting
  103. • Framework agnostic • Very flexible, not opinionated • Incrementally

    adoptable • Big community Apollo Client ___ https://www.apollographql.com/client
  104. Adding React Apollo https://www.apollographql.com/docs/react/

  105. https://twitter.com/dan_abramov/status/984951104315195392 Installing npm packages

  106. Configuring Apollo Client

  107. Wrapping a component to get data

  108. Defining GraphQL query

  109. Loading GraphQL query https://github.com/apollographql/graphql-tag

  110. Fetching data

  111. Using the data

  112. Code generation https://github.com/apollographql/apollo-codegen

  113. Introspecting schema and building JS type definitions

  114. Flow: incremental JS static type checking https://flow.org/

  115. Adding type annotations

  116. Server changes GraphQL schema

  117. Client validates query and code even before releasing it!

  118. • GraphQL clients • Consuming GraphQL API with modern JavaScript

    tools • Client-side code generation • Seemless integration – contract testing Part 3: Consuming GraphQL
  119. • GraphQL clients • Consuming GraphQL API with modern JavaScript

    tools • Client-side code generation • Seemless integration – contract testing Part 3: Consuming GraphQL
  120. With great flexibility on the client-side comes great responsibility on

    the server-side. Let’s make our GraphQL API more robust
  121. • Error handling • Authorization • Monitoring • Solving N+1

    queries Part 4: Making GraphQL API more robust
  122. Error handling https://github.com/exAspArk/graphql-errors

  123. Error handling

  124. Error handling

  125. Authorization https://github.com/exAspArk/graphql-guard

  126. Pass current user through context

  127. Define authorization logic

  128. Customize authorization error handling

  129. Authorization

  130. Monitoring https://github.com/uniiverse/apollo-tracing-ruby

  131. Collect trace data per field https://github.com/apollographql/apollo-tracing

  132. Expose trace data through GraphQL extensions https://facebook.github.io/graphql/October2016/#sec-Response-Format

  133. Apollo Engine https://www.apollographql.com/engine • Query execution tracing per field •

    GraphQL error tracking • Caching • Alerts • Free for up to 1 million requests per month
  134. Send tracing data to Engine

  135. Send tracing data to Engine https://github.com/uniiverse/apollo-tracing-ruby#engine-proxy

  136. N+1 queries

  137. N+1 queries

  138. I know the answer! https://giphy.com/gifs/cbc-funny-comedy-mr-d-xT9DPFPfULYJHHrqN2

  139. I know the answer!

  140. Solving N+1 queries https://github.com/exAspArk/batch-loader

  141. Tell GraphQL to consider BatchLoader instances as lazy objects

  142. Batch and cache

  143. Batch and cache

  144. Batch and cache

  145. Batch and cache

  146. Batch and cache https://engineering.universe.com/batching-a-powerful-way-to-solve-n-1-queries-every-rubyist-should-know-24e20c6e7b94

  147. Batch and cache https://engineering.universe.com/batching-a-powerful-way-to-solve-n-1-queries-every-rubyist-should-know-24e20c6e7b94

  148. No N+1 queries! __

  149. • Error handling • Authorization • Monitoring • Solving N+1

    queries Part 4: Making GraphQL API more robust
  150. • Error handling • Authorization • Monitoring • Solving N+1

    queries Part 4: Making GraphQL API more robust
  151. Takeaways • GraphQL is a specification • Getting the data

    you need, no under-fetching / over-fetching • Strong type system for documentation and seamless integration • Incrementally adoptable on client-side / server-side (7y old Rails app __) • Simpler to understand for junior developers: • Server-side: no routes, controllers, serializers, better composition • Client-side: no manual data fetching, mapping, caching (Redux)
  152. Takeaways • GraphQL is a specification • Getting the data

    you need, no under-fetching / over-fetching • Strong type system for documentation and seamless integration • Incrementally adoptable on client-side / server-side (7y old Rails app __) • Simpler to understand for junior developers: • Server-side: no routes, controllers, serializers, better composition • Client-side: no manual data fetching, mapping, caching (Redux) Conceptual compression!
  153. When to use GraphQL? Always

  154. When to use GraphQL? Always

  155. When to use GraphQL? • You have more than one

    API client (e.g. web + mobile app) • You care about latency and bandwidth (e.g. mobile networks) • You need a large API which you’re planning to change over time • You have multiple data sources (services, databases) and you need one API gateway
  156. Thank you! https://giphy.com/gifs/student-JU6TzB6O9QCju

  157. What we didn’t cover • Testing GraphQL • Pagination: limit

    / offset vs. cursor-based • Versioning, schema masking, stitching, delegation • Caching • Persisted queries • Query depth / complexity • Mutations for changing state on client-side / server-side • Subscriptions