SlideShare uma empresa Scribd logo
1 de 61
Baixar para ler offline
GRAPHQL & RELAY MODERN
JS ROUNDABOUT MEETUP JUNE 2017
Brad Pillow

Chief Software Architect at WorkHere LLC
GRAPHQL ☛ SERVER SIDE
RELAY ☛ CLIENT SIDE
REST
REST HISTORY
▸ The term representational state transfer was introduced and
defined in 2000 by Roy Fielding
▸ The defacto standard for communicating with a server
▸ Defines simple operations: GET, PUT, POST, DELETE
▸ A query operation (like GET) promises no side-effects (e.g.
changes) in data being queried. Commands (like PUT/
DELETE) answer no questions about the data, but compute
changes applied to the data (e.g. UPDATE or INSERT to use
database terms).
REST
REST ISSUES
▸ Many endpoints - proliferation of ad hoc endpoints
▸ Many round trips between the client and server
▸ First fetch pilots, then fetch home-world info for each pilot, then…
▸ Very expensive for mobile apps
▸ Response structure may change over time
▸ Data over-fetching
▸ We don’t always need all the data for a REST call
▸ Usually no metadata
▸ Big blob of data…we can’t run inquires on it’s types or structure

GRAPHQL
WHAT IS GRAPHQL?
▸ Queries describe the shape of data that the client needs. The
response has the same structure as the request query.
▸ Server interprets GraphQL calls and queries the database (or
any other source of data)
▸ GraphQL is language-, database- and protocol-agnostic 

GRAPHQL WAS
INVENTED AT FACEBOOK
IN 2012, BUT IT WAS
FIRST SHOWN TO
PUBLIC IN 2015 DURING
REACT.JS CONF AS A
PART OF FACEBOOK
OPEN-SOURCE
ECOSYSTEM.
GRAPHQL
GRAPHQL MOTIVATION
▸ Single endpoint - especially useful in server-less deployment
▸ Hierarchical nature
▸ Strongly typed - queries are validates against types…finds bugs more
quickly!
▸ Response mirrors the query
▸ Introspection - clients can discover the scheme and types (see GraphiQL)
▸ Application-Layer Protocol
▸ GraphQL is an application-layer protocol and does not require a particular
transport. It is a string that is parsed and interpreted by a server.
GRAPHQL
GRAPHQL IS “VERSION FREE”
▸ When adding new product features, additional fields can be
added to the server, leaving existing clients unaffected.
When you're removing older features, the corresponding
server fields can be deprecated but continue to function.
▸ Gradual, backward-compatible process which removes the
need for an incrementing version number
▸ Facebook still supports three years of released Facebook
applications on the same version of their GraphQL API 

GRAPHQL
GRAPHS - DAG/AST
*
-
397
+
6
DIRECTED ACYCLIC GRAPH ABSTRACT SYNTAX TREES
(6 + 7) * (9 - 3)
GRAPHQL
GRAPHS PERSON
[NAME, ID, …]
STARSHIP-A
[ID, MANUF,..]
STARSHIP-B
[ID, MANUF,..]
STARSHIP-C
[ID, MANUF,..]
PILOT-A
[ID, NAME,..]
STARSHIPCONNECTION
STARSHIPCONNECTION
STARSHIP CONNECTION
PILOT CONNECTION
HOMEWORLD-A
[ID, NAME,..]
HOMEWORLD CONNECTION
HOMEWORLDCONNECTION
NODE
NODE
EDGE
GRAPHQL
FOLLOW ALONG!
▸ Go here and follow along with me
▸ http://graphql.org/swapi-graphql/
GRAPHQL
BASIC QUERY
GRAPHQL
NESTED FIELDS
GRAPHQL
CONNECTIONS
GRAPHQL
CONNECTION PAGINATION
GRAPHQL
FRAGMENTS
GRAPHQL
MORE FRAGMENTS
GRAPHQL
INTROSPECTION
GRAPHQL
ADVANCED
▸ Directives allow modification of query execution
▸ Conditionals, etc. (@skip, @include…)
▸ Field aliases
▸ Fetch multiple fields in a single query
▸ Fragments
▸ Reuse common fields/structures
▸ Inline fragments
▸ Union types: discriminate based on runtime type
GRAPHQL
STILL MORE…
▸ Syntax ✔
▸ Type System
▸ Resolving
▸ Edges/Nodes & Pagination
GRAPHQL
GRAPHQL TYPE SYSTEM
▸ Scalars - basic types
▸ Schema - a representation of the capabilities of the GraphQL
server
▸ Definitions - defining types
GRAPHQL
GRAPHQL SCALARS
▸ GraphQLInt - integer number
▸ GraphQLFloat - float number
▸ GraphQLString - string
▸ GraphQLBoolean - boolean
▸ GraphQLID - represents an ID (essentially a string)
GRAPHQL
GRAPHQL SCHEMAS
▸ It all starts with a “root” query
▸ Fields on type can be plain data or “resolved”
▸ You can define your own types
▸ You can define/override the serialization on a type
▸ You can add enhanced validation to types
▸ From a schema, you can generate a more human readable
schema and JSON based schema for clients to use
GRAPHQL
GRAPHQL DEFINITIONS
▸ GraphQLScalarType - the class of scalars
▸ GraphQLObjectType - an object
▸ GraphQLInterfaceType - a interface
▸ GraphQLUnionType - a union
▸ GraphQLEnumType - enum
▸ GraphQLInputObjectType
▸ GraphQLList - what you use for lists arrays of objects
▸ GraphQLNonNull - an object for which null is an invalid value
GRAPHQL
GRAPHQL QUERY/MUTATION RESOLUTION
GRAPHQL
GRAPHQL EDGES/NODES
▸ Not built into the language, but provided by types
▸ The type Facebook uses and I recommend you use too, are in
: https://github.com/graphql/graphql-relay-js
▸ Using edges and nodes allow for pagination. If you don’t
need pagination, then use a simple GraphQLList.
GRAPHQL
RUNNING ON EXPRESS https://github.com/graphql/graphql-js
GRAPHQL
EXAMPLE SCHEMA
GRAPHQL
CUSTOM SCALAR
TEXT
DATA LOADER
▸ Way too many hits to my
database
▸ Data loader is basically a
simple caching
mechanism
▸ Example: deeply nested
queries can result in
multiple database
queries for the same
data
TEXT
DATA LOADER - EXAMPLE
GRAPHQL
GRAPHQL MISUNDERSTANDINGS
▸ All of the queries you see are defined by your schema. I.e.
things like viewer, user, edge, node are defined by the
schema and not an inherent part of the language.
▸ GraphQL is Javascript only. Nope!
▸ There are 3rd party ports for ReasonML, Python, Scala, Go, Ruby, etc.
▸ GraphQL requires special communications protocol. Nope!
▸ The default implementation uses a basic REST post call, but you can use
web sockets, etc. and even mix and match.
RELAY MODERN
RELAY MODERN
WHAT RELAY PROVIDES
▸ DECLARATIVE
▸ Declare what you want and let Relay and GraphQL worry about requests, validation and caching.
▸ COLOCATION
▸ Keep queries with the code to display them.
▸ MUTATIONS
▸ Change data on the server and get automatic data consistency, optimistic updates and error
handling.
▸ Works on React and React-Native.
▸ Relay Modern is view framework agnostic.
RELAY MODERN
RELAY STORE
COMPONENTS
MUTATION
RELAY
SERVER
GraphQL Write (mutation)
Optimistic
Update
GraphQL Query
GraphQL Response
RELAY MODERN
TERMINOLOGY
▸ Container - HOC for your component (createFragmentContainer)
▸ Refetching Data - aka "See More” - allows fetching more data
(createRefetchContainer)
▸ Pagination Container - handle more complicated connection
pagination (createPaginationContainer)
▸ Query Renderer - HOC to handle exciting queries and fetching data to
your components (QueryRenderer)
▸ Relay Environment - the bundle of the store/cache and network layer
▸ Network Layer - abstracted to allow different networks
RELAY MODERN
WHAT’S NEW
▸ Performance
▸ Size - 20% smaller
▸ Garbage Collection - saves on memory
▸ Injectable Custom Field Handlers - field post processing
▸ Subscriptions (push) & Live Queries (polling)
RELAY MODERN
MORE WHAT’S NEW
▸ Simpler Mutation API - MUCH simpler for most cases
▸ Client Schema Extensions - local schema, merged with remote…
can replace redux/Mobx
▸ Flow Type Generation - type check your query results
▸ Much Simpler Routing
▸ Not Tied To React anymore
▸ Static queries (i.e. a query is pre-stored on the server, so the query
is sent to the server with a single “query ID”…less query traffic)
TEXT
FOLLOW ALONG!
▸ https://facebook.github.io/relay
RELAY
EXAMPLE: SIMPLE - HELLO WORLD - SCHEMA
RELAY CLASSIC
EXAMPLE: SIMPLE - HELLO WORLD -COMPONENTS
RELAY CLASSIC
RELAY
EXAMPLE: LIST - GRAPHQL SCHEMA
RELAY CLASSIC
EXAMPLE: LIST - COMPONENTS
RELAY CLASSIC
RELAY
EXAMPLES: PARAMETERS & MUTATIONS
Relay query fragments can be parameterized using
variables in GraphQL calls. This enables mechanics
like pagination, filtering, sorting, and more.
Use Relay to change the world through the use of
GraphQL mutations. Given a set of query fragments, a
mutation and a set of behaviors to exhibit when the
server responds (the ‘query configs’), Relay will
ensure that all of the data necessary to perform the
mutation has been fetched, and that your client-side
data stays in sync with the server after the mutation.
Try the examples out here: https://facebook.github.io/relay/
RELAY
RELAY MISUNDERSTANDINGS
▸ ID’s - they’re needed from GraphQL to handle cache
coherency and management
▸ if you don’t provide unique “global ids” then Relay won’t work correctly
▸ How can I refresh my data if the server data changes?
▸ Subscriptions - new
▸ Can also force a “refetch”
RELAY
SUBSCRIPTIONS
▸ Think of subscriptions as mutation observables (mapped by
subscription ID) on the server side. When an observable
changes, notify client (pub/sub) and perform a local mutation
(force update).
▸ Another option: use forceUpdate on route changes in react-
router-relay
RELAY
SUBSCRIPTIONS DEEPER DIVE
▸ In the GraphQL server, subscriptions are implemented/
defined by returning “subscribe” field, which is an async
iterator.
▸ We are all familiar with iterators, which allow us to step
through arrays and other iterables:
▸ [1,2,3].forEach(value => console.log(value));
▸ Generators (i.e. function *()) are also iterables.
RELAY
ASYNC ITERATORS
/**
* Returns a promise which resolves after time had passed.
*/
const delay = time => new Promise(resolve => setTimeout(resolve, time));
async function* delayedRange(max) {
    for (let i = 0; i < max; i++) {
        await delay(1000);
        yield i;
    }
}
for await (let number of delayedRange(10)) {
    console.log(number);
}
Needs: ’babel-plugin-transform-async-generator-functions'
GRAPHQL
GRAPHQL SUBSCRIPTION RESOLUTION
▸ Fields resolve to an async
iterator that will return data
over time. Async iterators are
iterators that return a promise
on each step, rather than an
object. They are similar to
Observables in RxJS.
GRAPHQL
GRAPHQL SUBSCRIPTION PUBSUB TO RELAY CLIENT
▸ With your GraphQL schema resolving
subscriptions to async iterators, you
need to somehow get the results of
those iterators to the relay client.
▸ This is typically done with websockets or
some other pub/sub mechanism.
▸ On the Relay side, the published
subscription data is captured and used
to modify the Relay Store.
▸ Typically your client side pub/sub will
need act interface-wise as an
observable.
GRAPHQL
RELAY SUBSCRIPTIONS…ADVANCED…
▸ For simple subscriptions, I.e.
those that are just updating an
object in the store (specified by
the data and ID in the payload),
no updater is needed.
▸ For subscriptions adding/
deleting data/connections, then
an updater is needed.
GRAPHQL
RELAY SUBSCRIPTION HANDLING
▸ Fields resolve to an async
iterator that will return data
over time. Async iterators are
iterators that return a promise
on each step, rather than an
object. They are similar to
Observables in RxJS.
RELAY
ROUTING
▸ In relay-modern, no specific routing is needed. You can use
react-router, react-navigation or whatever works with relay.
RELAY
BABEL-PLUGIN-RELAY & RELAY COMPILER
▸ In relay-classic you only need a babel relay plugin to
transpile the GraphQL tagged template strings. In relay-
modern, you need to run the relay compiler on your source
first. This precompiles the queries for faster execution (no
runtime parsing) and creates flow types for your queries.
TEXT
DEBUGGING
▸ Your own network layer, turn on Relay transport logging in
debug
▸ Web sockets
TEXT
LOCAL RELAY
▸ If you look at Relay, it seems a lot like Redux
▸ Can we use Relay to replace redux? In relay-modern…yes!
▸ WorkHere uses relay in a local way to allow for faster
graphql. We do this by having a local schema, that talks to
Firebase via the local Firebase package (which talks to
Firebase vis web sockets).
GRAPHQL & RELAY: SERVERLESS
SERVERLESS GRAPHQL
▸ Google Cloud Functions - https://cloud.google.com/functions/
docs/
▸ AWS Lambda - https://github.com/serverless/serverless-
graphql
GRAPHQL & RELAY: RESOURCES
GAAS - GRAPHQL AS A SERVICE
▸ Scaphold - https://scaphold.io/
▸ GraphCool - https://www.graph.cool/
▸ ReIndex - https://www.reindex.io/baas/
GRAPHQL & RELAY: RESOURCES
RESOURCES
▸ Cartoon Guides To GraphQL & Relay: https://code-
cartoons.com
▸ Awesome GraphQL - curated list on Github: https://github.com/
chentsulin/awesome-graphql
▸ GraphQL Schema Visualizer CLI - https://github.com/sheerun/
graphqlviz
▸ GraphQL Schema Visualizer Web - http://nathanrandal.com/
graphql-visualizer/
GRAPHQL & RELAY: RESOURCES
MORE RESOURCES
▸ Relay Home: https://facebook.github.io/relay/
▸ GraphQL Home: http://graphql.org/
▸ GraphQL Spec: https://facebook.github.io/graphql/
▸ Many REST APIs you can experiment with using GraphQL: https://
www.graphqlhub.com/
▸ React Playground - Try It Live: https://facebook.github.io/relay/
prototyping/playground.html#/
▸ GraphQL Hub - Reddit, Hacker News, GitHub, etc. - https://
www.graphqlhub.com/
QUESTIONS???▸ Twitter: @BradPillow, GitHub: pillowsoft
▸ Meetup repo on GitHub: carmel-javascript-roundabout
THANKS!

Mais conteúdo relacionado

Mais procurados

Event sourcing - what could possibly go wrong ? Devoxx PL 2021
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Event sourcing - what could possibly go wrong ? Devoxx PL 2021Andrzej Ludwikowski
 
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache KafkaSolutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache KafkaGuido Schmutz
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Guido Schmutz
 
Location Analytics - Real-Time Geofencing using Kafka
Location Analytics - Real-Time Geofencing using Kafka Location Analytics - Real-Time Geofencing using Kafka
Location Analytics - Real-Time Geofencing using Kafka Guido Schmutz
 
Spark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsSpark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsGuido Schmutz
 
Location Analytics - Real Time Geofencing using Apache Kafka
Location Analytics - Real Time Geofencing using Apache KafkaLocation Analytics - Real Time Geofencing using Apache Kafka
Location Analytics - Real Time Geofencing using Apache KafkaGuido Schmutz
 
Introduction to Stream Processing
Introduction to Stream ProcessingIntroduction to Stream Processing
Introduction to Stream ProcessingGuido Schmutz
 
Performance Analysis and Optimizations for Kafka Streams Applications
Performance Analysis and Optimizations for Kafka Streams ApplicationsPerformance Analysis and Optimizations for Kafka Streams Applications
Performance Analysis and Optimizations for Kafka Streams ApplicationsGuozhang Wang
 
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...ScyllaDB
 
Event Hub (i.e. Kafka) in Modern Data Architecture
Event Hub (i.e. Kafka) in Modern Data ArchitectureEvent Hub (i.e. Kafka) in Modern Data Architecture
Event Hub (i.e. Kafka) in Modern Data ArchitectureGuido Schmutz
 
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...DataWorks Summit
 
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...Databricks
 
Serverless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipelineServerless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipelineShu-Jeng Hsieh
 
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch - Dynami...
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch -  Dynami...Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch -  Dynami...
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch - Dynami...Flink Forward
 
ksqlDB - Stream Processing simplified!
ksqlDB - Stream Processing simplified!ksqlDB - Stream Processing simplified!
ksqlDB - Stream Processing simplified!Guido Schmutz
 
C*ollege Credit: CEP Distribtued Processing on Cassandra with Storm
C*ollege Credit: CEP Distribtued Processing on Cassandra with StormC*ollege Credit: CEP Distribtued Processing on Cassandra with Storm
C*ollege Credit: CEP Distribtued Processing on Cassandra with StormDataStax
 
Google Dataflow Intro
Google Dataflow IntroGoogle Dataflow Intro
Google Dataflow IntroIvan Glushkov
 

Mais procurados (20)

Event sourcing - what could possibly go wrong ? Devoxx PL 2021
Event sourcing  - what could possibly go wrong ? Devoxx PL 2021Event sourcing  - what could possibly go wrong ? Devoxx PL 2021
Event sourcing - what could possibly go wrong ? Devoxx PL 2021
 
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache KafkaSolutions for bi-directional integration between Oracle RDBMS & Apache Kafka
Solutions for bi-directional integration between Oracle RDBMS & Apache Kafka
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
 
Location Analytics - Real-Time Geofencing using Kafka
Location Analytics - Real-Time Geofencing using Kafka Location Analytics - Real-Time Geofencing using Kafka
Location Analytics - Real-Time Geofencing using Kafka
 
Omid: A Transactional Framework for HBase
Omid: A Transactional Framework for HBaseOmid: A Transactional Framework for HBase
Omid: A Transactional Framework for HBase
 
Spark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsSpark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka Streams
 
Data Pipeline at Tapad
Data Pipeline at TapadData Pipeline at Tapad
Data Pipeline at Tapad
 
Location Analytics - Real Time Geofencing using Apache Kafka
Location Analytics - Real Time Geofencing using Apache KafkaLocation Analytics - Real Time Geofencing using Apache Kafka
Location Analytics - Real Time Geofencing using Apache Kafka
 
Introduction to Stream Processing
Introduction to Stream ProcessingIntroduction to Stream Processing
Introduction to Stream Processing
 
Performance Analysis and Optimizations for Kafka Streams Applications
Performance Analysis and Optimizations for Kafka Streams ApplicationsPerformance Analysis and Optimizations for Kafka Streams Applications
Performance Analysis and Optimizations for Kafka Streams Applications
 
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...
Simplifying the Creation of Machine Learning Workflow Pipelines for IoT Appli...
 
Event Hub (i.e. Kafka) in Modern Data Architecture
Event Hub (i.e. Kafka) in Modern Data ArchitectureEvent Hub (i.e. Kafka) in Modern Data Architecture
Event Hub (i.e. Kafka) in Modern Data Architecture
 
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...
Optimizing Geospatial Operations with Server-side Programming in HBase and Ac...
 
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
A Practical Approach to Building a Streaming Processing Pipeline for an Onlin...
 
Serverless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipelineServerless ETL and Optimization on ML pipeline
Serverless ETL and Optimization on ML pipeline
 
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch - Dynami...
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch -  Dynami...Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch -  Dynami...
Flink Forward SF 2017: David Hardwick, Sean Hester & David Brelloch - Dynami...
 
ksqlDB - Stream Processing simplified!
ksqlDB - Stream Processing simplified!ksqlDB - Stream Processing simplified!
ksqlDB - Stream Processing simplified!
 
C*ollege Credit: CEP Distribtued Processing on Cassandra with Storm
C*ollege Credit: CEP Distribtued Processing on Cassandra with StormC*ollege Credit: CEP Distribtued Processing on Cassandra with Storm
C*ollege Credit: CEP Distribtued Processing on Cassandra with Storm
 
Google Dataflow Intro
Google Dataflow IntroGoogle Dataflow Intro
Google Dataflow Intro
 
EMR AWS Demo
EMR AWS DemoEMR AWS Demo
EMR AWS Demo
 

Semelhante a GraphQL & Relay Meetup

GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016Brad Pillow
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part DeuxBrad Pillow
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherSashko Stubailo
 
GraphQL & DGraph with Go
GraphQL & DGraph with GoGraphQL & DGraph with Go
GraphQL & DGraph with GoJames Tan
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentationVibhor Grover
 
How easy (or hard) it is to monitor your graph ql service performance
How easy (or hard) it is to monitor your graph ql service performanceHow easy (or hard) it is to monitor your graph ql service performance
How easy (or hard) it is to monitor your graph ql service performanceLuca Mattia Ferrari
 
How to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayHow to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayQAware GmbH
 
Cascading on starfish
Cascading on starfishCascading on starfish
Cascading on starfishFei Dong
 
Scaling your GraphQL applications with Dgraph
Scaling your GraphQL applications with DgraphScaling your GraphQL applications with Dgraph
Scaling your GraphQL applications with DgraphKarthic Rao
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLRodrigo Prates
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPAndrew Rota
 
Cloud Native Applications on OpenShift
Cloud Native Applications on OpenShiftCloud Native Applications on OpenShift
Cloud Native Applications on OpenShiftSerhat Dirik
 
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuseapidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuseapidays
 
Giga Spaces Data Grid / Data Caching Overview
Giga Spaces Data Grid / Data Caching OverviewGiga Spaces Data Grid / Data Caching Overview
Giga Spaces Data Grid / Data Caching Overviewjimliddle
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...François-Guillaume Ribreau
 
Coherence RoadMap 2018
Coherence RoadMap 2018Coherence RoadMap 2018
Coherence RoadMap 2018harvraja
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)Rob Crowley
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessConnected Data World
 

Semelhante a GraphQL & Relay Meetup (20)

GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part Deux
 
The GrapQL ecosystem
The GrapQL ecosystemThe GrapQL ecosystem
The GrapQL ecosystem
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
 
GraphQL & DGraph with Go
GraphQL & DGraph with GoGraphQL & DGraph with Go
GraphQL & DGraph with Go
 
Graphql presentation
Graphql presentationGraphql presentation
Graphql presentation
 
How easy (or hard) it is to monitor your graph ql service performance
How easy (or hard) it is to monitor your graph ql service performanceHow easy (or hard) it is to monitor your graph ql service performance
How easy (or hard) it is to monitor your graph ql service performance
 
How to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that wayHow to provide a GraphQL API - I want it that way
How to provide a GraphQL API - I want it that way
 
Cascading on starfish
Cascading on starfishCascading on starfish
Cascading on starfish
 
Scaling your GraphQL applications with Dgraph
Scaling your GraphQL applications with DgraphScaling your GraphQL applications with Dgraph
Scaling your GraphQL applications with Dgraph
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Tutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHPTutorial: Building a GraphQL API in PHP
Tutorial: Building a GraphQL API in PHP
 
Cloud Native Applications on OpenShift
Cloud Native Applications on OpenShiftCloud Native Applications on OpenShift
Cloud Native Applications on OpenShift
 
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuseapidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuse
 
Giga Spaces Data Grid / Data Caching Overview
Giga Spaces Data Grid / Data Caching OverviewGiga Spaces Data Grid / Data Caching Overview
Giga Spaces Data Grid / Data Caching Overview
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
 
Grails 101
Grails 101Grails 101
Grails 101
 
Coherence RoadMap 2018
Coherence RoadMap 2018Coherence RoadMap 2018
Coherence RoadMap 2018
 
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
GraphQL - A query language to empower your API consumers (NDC Sydney 2017)
 
GraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database accessGraphQL and its schema as a universal layer for database access
GraphQL and its schema as a universal layer for database access
 

Último

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Último (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

GraphQL & Relay Meetup

  • 1. GRAPHQL & RELAY MODERN JS ROUNDABOUT MEETUP JUNE 2017 Brad Pillow
 Chief Software Architect at WorkHere LLC
  • 2. GRAPHQL ☛ SERVER SIDE RELAY ☛ CLIENT SIDE
  • 3. REST REST HISTORY ▸ The term representational state transfer was introduced and defined in 2000 by Roy Fielding ▸ The defacto standard for communicating with a server ▸ Defines simple operations: GET, PUT, POST, DELETE ▸ A query operation (like GET) promises no side-effects (e.g. changes) in data being queried. Commands (like PUT/ DELETE) answer no questions about the data, but compute changes applied to the data (e.g. UPDATE or INSERT to use database terms).
  • 4. REST REST ISSUES ▸ Many endpoints - proliferation of ad hoc endpoints ▸ Many round trips between the client and server ▸ First fetch pilots, then fetch home-world info for each pilot, then… ▸ Very expensive for mobile apps ▸ Response structure may change over time ▸ Data over-fetching ▸ We don’t always need all the data for a REST call ▸ Usually no metadata ▸ Big blob of data…we can’t run inquires on it’s types or structure

  • 5. GRAPHQL WHAT IS GRAPHQL? ▸ Queries describe the shape of data that the client needs. The response has the same structure as the request query. ▸ Server interprets GraphQL calls and queries the database (or any other source of data) ▸ GraphQL is language-, database- and protocol-agnostic 

  • 6. GRAPHQL WAS INVENTED AT FACEBOOK IN 2012, BUT IT WAS FIRST SHOWN TO PUBLIC IN 2015 DURING REACT.JS CONF AS A PART OF FACEBOOK OPEN-SOURCE ECOSYSTEM.
  • 7. GRAPHQL GRAPHQL MOTIVATION ▸ Single endpoint - especially useful in server-less deployment ▸ Hierarchical nature ▸ Strongly typed - queries are validates against types…finds bugs more quickly! ▸ Response mirrors the query ▸ Introspection - clients can discover the scheme and types (see GraphiQL) ▸ Application-Layer Protocol ▸ GraphQL is an application-layer protocol and does not require a particular transport. It is a string that is parsed and interpreted by a server.
  • 8. GRAPHQL GRAPHQL IS “VERSION FREE” ▸ When adding new product features, additional fields can be added to the server, leaving existing clients unaffected. When you're removing older features, the corresponding server fields can be deprecated but continue to function. ▸ Gradual, backward-compatible process which removes the need for an incrementing version number ▸ Facebook still supports three years of released Facebook applications on the same version of their GraphQL API 

  • 9. GRAPHQL GRAPHS - DAG/AST * - 397 + 6 DIRECTED ACYCLIC GRAPH ABSTRACT SYNTAX TREES (6 + 7) * (9 - 3)
  • 10. GRAPHQL GRAPHS PERSON [NAME, ID, …] STARSHIP-A [ID, MANUF,..] STARSHIP-B [ID, MANUF,..] STARSHIP-C [ID, MANUF,..] PILOT-A [ID, NAME,..] STARSHIPCONNECTION STARSHIPCONNECTION STARSHIP CONNECTION PILOT CONNECTION HOMEWORLD-A [ID, NAME,..] HOMEWORLD CONNECTION HOMEWORLDCONNECTION NODE NODE EDGE
  • 11. GRAPHQL FOLLOW ALONG! ▸ Go here and follow along with me ▸ http://graphql.org/swapi-graphql/
  • 19. GRAPHQL ADVANCED ▸ Directives allow modification of query execution ▸ Conditionals, etc. (@skip, @include…) ▸ Field aliases ▸ Fetch multiple fields in a single query ▸ Fragments ▸ Reuse common fields/structures ▸ Inline fragments ▸ Union types: discriminate based on runtime type
  • 20. GRAPHQL STILL MORE… ▸ Syntax ✔ ▸ Type System ▸ Resolving ▸ Edges/Nodes & Pagination
  • 21. GRAPHQL GRAPHQL TYPE SYSTEM ▸ Scalars - basic types ▸ Schema - a representation of the capabilities of the GraphQL server ▸ Definitions - defining types
  • 22. GRAPHQL GRAPHQL SCALARS ▸ GraphQLInt - integer number ▸ GraphQLFloat - float number ▸ GraphQLString - string ▸ GraphQLBoolean - boolean ▸ GraphQLID - represents an ID (essentially a string)
  • 23. GRAPHQL GRAPHQL SCHEMAS ▸ It all starts with a “root” query ▸ Fields on type can be plain data or “resolved” ▸ You can define your own types ▸ You can define/override the serialization on a type ▸ You can add enhanced validation to types ▸ From a schema, you can generate a more human readable schema and JSON based schema for clients to use
  • 24. GRAPHQL GRAPHQL DEFINITIONS ▸ GraphQLScalarType - the class of scalars ▸ GraphQLObjectType - an object ▸ GraphQLInterfaceType - a interface ▸ GraphQLUnionType - a union ▸ GraphQLEnumType - enum ▸ GraphQLInputObjectType ▸ GraphQLList - what you use for lists arrays of objects ▸ GraphQLNonNull - an object for which null is an invalid value
  • 26. GRAPHQL GRAPHQL EDGES/NODES ▸ Not built into the language, but provided by types ▸ The type Facebook uses and I recommend you use too, are in : https://github.com/graphql/graphql-relay-js ▸ Using edges and nodes allow for pagination. If you don’t need pagination, then use a simple GraphQLList.
  • 27. GRAPHQL RUNNING ON EXPRESS https://github.com/graphql/graphql-js
  • 30. TEXT DATA LOADER ▸ Way too many hits to my database ▸ Data loader is basically a simple caching mechanism ▸ Example: deeply nested queries can result in multiple database queries for the same data
  • 32. GRAPHQL GRAPHQL MISUNDERSTANDINGS ▸ All of the queries you see are defined by your schema. I.e. things like viewer, user, edge, node are defined by the schema and not an inherent part of the language. ▸ GraphQL is Javascript only. Nope! ▸ There are 3rd party ports for ReasonML, Python, Scala, Go, Ruby, etc. ▸ GraphQL requires special communications protocol. Nope! ▸ The default implementation uses a basic REST post call, but you can use web sockets, etc. and even mix and match.
  • 34. RELAY MODERN WHAT RELAY PROVIDES ▸ DECLARATIVE ▸ Declare what you want and let Relay and GraphQL worry about requests, validation and caching. ▸ COLOCATION ▸ Keep queries with the code to display them. ▸ MUTATIONS ▸ Change data on the server and get automatic data consistency, optimistic updates and error handling. ▸ Works on React and React-Native. ▸ Relay Modern is view framework agnostic.
  • 35. RELAY MODERN RELAY STORE COMPONENTS MUTATION RELAY SERVER GraphQL Write (mutation) Optimistic Update GraphQL Query GraphQL Response
  • 36. RELAY MODERN TERMINOLOGY ▸ Container - HOC for your component (createFragmentContainer) ▸ Refetching Data - aka "See More” - allows fetching more data (createRefetchContainer) ▸ Pagination Container - handle more complicated connection pagination (createPaginationContainer) ▸ Query Renderer - HOC to handle exciting queries and fetching data to your components (QueryRenderer) ▸ Relay Environment - the bundle of the store/cache and network layer ▸ Network Layer - abstracted to allow different networks
  • 37. RELAY MODERN WHAT’S NEW ▸ Performance ▸ Size - 20% smaller ▸ Garbage Collection - saves on memory ▸ Injectable Custom Field Handlers - field post processing ▸ Subscriptions (push) & Live Queries (polling)
  • 38. RELAY MODERN MORE WHAT’S NEW ▸ Simpler Mutation API - MUCH simpler for most cases ▸ Client Schema Extensions - local schema, merged with remote… can replace redux/Mobx ▸ Flow Type Generation - type check your query results ▸ Much Simpler Routing ▸ Not Tied To React anymore ▸ Static queries (i.e. a query is pre-stored on the server, so the query is sent to the server with a single “query ID”…less query traffic)
  • 40. RELAY EXAMPLE: SIMPLE - HELLO WORLD - SCHEMA
  • 41. RELAY CLASSIC EXAMPLE: SIMPLE - HELLO WORLD -COMPONENTS RELAY CLASSIC
  • 42. RELAY EXAMPLE: LIST - GRAPHQL SCHEMA
  • 43. RELAY CLASSIC EXAMPLE: LIST - COMPONENTS RELAY CLASSIC
  • 44. RELAY EXAMPLES: PARAMETERS & MUTATIONS Relay query fragments can be parameterized using variables in GraphQL calls. This enables mechanics like pagination, filtering, sorting, and more. Use Relay to change the world through the use of GraphQL mutations. Given a set of query fragments, a mutation and a set of behaviors to exhibit when the server responds (the ‘query configs’), Relay will ensure that all of the data necessary to perform the mutation has been fetched, and that your client-side data stays in sync with the server after the mutation. Try the examples out here: https://facebook.github.io/relay/
  • 45. RELAY RELAY MISUNDERSTANDINGS ▸ ID’s - they’re needed from GraphQL to handle cache coherency and management ▸ if you don’t provide unique “global ids” then Relay won’t work correctly ▸ How can I refresh my data if the server data changes? ▸ Subscriptions - new ▸ Can also force a “refetch”
  • 46. RELAY SUBSCRIPTIONS ▸ Think of subscriptions as mutation observables (mapped by subscription ID) on the server side. When an observable changes, notify client (pub/sub) and perform a local mutation (force update). ▸ Another option: use forceUpdate on route changes in react- router-relay
  • 47. RELAY SUBSCRIPTIONS DEEPER DIVE ▸ In the GraphQL server, subscriptions are implemented/ defined by returning “subscribe” field, which is an async iterator. ▸ We are all familiar with iterators, which allow us to step through arrays and other iterables: ▸ [1,2,3].forEach(value => console.log(value)); ▸ Generators (i.e. function *()) are also iterables.
  • 48. RELAY ASYNC ITERATORS /** * Returns a promise which resolves after time had passed. */ const delay = time => new Promise(resolve => setTimeout(resolve, time)); async function* delayedRange(max) {     for (let i = 0; i < max; i++) {         await delay(1000);         yield i;     } } for await (let number of delayedRange(10)) {     console.log(number); } Needs: ’babel-plugin-transform-async-generator-functions'
  • 49. GRAPHQL GRAPHQL SUBSCRIPTION RESOLUTION ▸ Fields resolve to an async iterator that will return data over time. Async iterators are iterators that return a promise on each step, rather than an object. They are similar to Observables in RxJS.
  • 50. GRAPHQL GRAPHQL SUBSCRIPTION PUBSUB TO RELAY CLIENT ▸ With your GraphQL schema resolving subscriptions to async iterators, you need to somehow get the results of those iterators to the relay client. ▸ This is typically done with websockets or some other pub/sub mechanism. ▸ On the Relay side, the published subscription data is captured and used to modify the Relay Store. ▸ Typically your client side pub/sub will need act interface-wise as an observable.
  • 51. GRAPHQL RELAY SUBSCRIPTIONS…ADVANCED… ▸ For simple subscriptions, I.e. those that are just updating an object in the store (specified by the data and ID in the payload), no updater is needed. ▸ For subscriptions adding/ deleting data/connections, then an updater is needed.
  • 52. GRAPHQL RELAY SUBSCRIPTION HANDLING ▸ Fields resolve to an async iterator that will return data over time. Async iterators are iterators that return a promise on each step, rather than an object. They are similar to Observables in RxJS.
  • 53. RELAY ROUTING ▸ In relay-modern, no specific routing is needed. You can use react-router, react-navigation or whatever works with relay.
  • 54. RELAY BABEL-PLUGIN-RELAY & RELAY COMPILER ▸ In relay-classic you only need a babel relay plugin to transpile the GraphQL tagged template strings. In relay- modern, you need to run the relay compiler on your source first. This precompiles the queries for faster execution (no runtime parsing) and creates flow types for your queries.
  • 55. TEXT DEBUGGING ▸ Your own network layer, turn on Relay transport logging in debug ▸ Web sockets
  • 56. TEXT LOCAL RELAY ▸ If you look at Relay, it seems a lot like Redux ▸ Can we use Relay to replace redux? In relay-modern…yes! ▸ WorkHere uses relay in a local way to allow for faster graphql. We do this by having a local schema, that talks to Firebase via the local Firebase package (which talks to Firebase vis web sockets).
  • 57. GRAPHQL & RELAY: SERVERLESS SERVERLESS GRAPHQL ▸ Google Cloud Functions - https://cloud.google.com/functions/ docs/ ▸ AWS Lambda - https://github.com/serverless/serverless- graphql
  • 58. GRAPHQL & RELAY: RESOURCES GAAS - GRAPHQL AS A SERVICE ▸ Scaphold - https://scaphold.io/ ▸ GraphCool - https://www.graph.cool/ ▸ ReIndex - https://www.reindex.io/baas/
  • 59. GRAPHQL & RELAY: RESOURCES RESOURCES ▸ Cartoon Guides To GraphQL & Relay: https://code- cartoons.com ▸ Awesome GraphQL - curated list on Github: https://github.com/ chentsulin/awesome-graphql ▸ GraphQL Schema Visualizer CLI - https://github.com/sheerun/ graphqlviz ▸ GraphQL Schema Visualizer Web - http://nathanrandal.com/ graphql-visualizer/
  • 60. GRAPHQL & RELAY: RESOURCES MORE RESOURCES ▸ Relay Home: https://facebook.github.io/relay/ ▸ GraphQL Home: http://graphql.org/ ▸ GraphQL Spec: https://facebook.github.io/graphql/ ▸ Many REST APIs you can experiment with using GraphQL: https:// www.graphqlhub.com/ ▸ React Playground - Try It Live: https://facebook.github.io/relay/ prototyping/playground.html#/ ▸ GraphQL Hub - Reddit, Hacker News, GitHub, etc. - https:// www.graphqlhub.com/
  • 61. QUESTIONS???▸ Twitter: @BradPillow, GitHub: pillowsoft ▸ Meetup repo on GitHub: carmel-javascript-roundabout THANKS!