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
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
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.
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.
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)
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.
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).