0% found this document useful (0 votes)
31 views28 pages

Making SPA Smarter With GraphQL

The document provides information about a presentation on GraphQL at the Philly Emerging Technologies for the Enterprise 2019 conference. The presentation titled "Making SPA [Smarter!]! (?) with GraphQL" will be given by Ken Rimple, Director of Training and Mentoring at Chariot Solutions. GraphQL is presented as an alternative to REST APIs that allows fetching and updating data via a graph-like hierarchy defined by a schema. Benefits include fetching only needed data and capabilities for queries, mutations, and subscriptions. Examples of GraphQL schemas, queries, and mutations are provided.

Uploaded by

1977am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views28 pages

Making SPA Smarter With GraphQL

The document provides information about a presentation on GraphQL at the Philly Emerging Technologies for the Enterprise 2019 conference. The presentation titled "Making SPA [Smarter!]! (?) with GraphQL" will be given by Ken Rimple, Director of Training and Mentoring at Chariot Solutions. GraphQL is presented as an alternative to REST APIs that allows fetching and updating data via a graph-like hierarchy defined by a schema. Benefits include fetching only needed data and capabilities for queries, mutations, and subscriptions. Examples of GraphQL schemas, queries, and mutations are provided.

Uploaded by

1977am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

WIFI HASHTAG SESSION Q&A

ETE2019 #PhillyETE Visit sli.do


#PHILLYETE

Presented By
Making SPA [Smarter!]! (?)
with GraphQL

Ken Rimple
Director, Training and Mentoring - Chariot Solutions
Philly Emerging Technologies for the Enterprise 2019
Graph Querying Language
• Data is fetched and updated via a graph-like hierarchy of objects

• Graph is defined by a schema of:

• Data types

• Queries

• Mutations

• Subscriptions
An alternative to REST APIs

• Shift from HTTP-based concepts to RPC-style

• Queries - read-only information from your graph

• Mutations - any modification to data in your graph

• Subscriptions - read-only queries, refreshed automatically from the


server
Language Benefits

• Well-defined schema

• Useful query and analysis tools for developers

• Query/mutate/subscribe to what you need

• Open metadata querying API

• Can be queried even from simple web service calls or curl


A simple GraphQL Schema
type Query {
getQuizzes: [Quiz!]
Queries provide data based
getQuiz(id: Int!): Quiz! on GraphQL Types
}

type Quiz {
id: Int! Types are defined based
on primitives such as
name: String!
Int, String, Boolean
description: String! and other types
}
Query with GraphQL
import {client} from './apollo-graphql-client';
import gql from 'graphql-tag';

export function getQuizzesQuery() { This is an Apollo client,


but most of the
return client.query({
differences are in setup,
fetchPolicy: 'no-cache', not in query syntax
query: gql`
{ The meat of the call
getQuizzes { Is just GraphQL
name query syntax
}
}`
});
}
Mutations can Return Data
type Mutation {
voteOnCurrentQuestion(answer: String): ScoreData!
}

Mutations change your data, type ScoreData {


correct: Boolean!
and can also return results points: Int
like a query }
Mutations with Complex Input
type Mutation {
login(credentials: SignInCredentials): String
}

Special input types input SignInCredentials {


are only allowed to send userName: String!
Parameter sets to a query password: String!
}
or mutation
Sample Mutation Call
Query signature includes
param name and type
await client.mutate({
mutation: gql`
mutation answerQuestion($answer: QuestionAnswerInput!) {
answerQuestion (input: $answer)
}`,
Actual schema mutation param
variables: {
name and substitution variable
{
answer: { key: incomingKey, quiz: incomingQuizId }
}
}
}); Map to variables incomingKey
and incomingQuizId from
JavaScript function params
GraphQL Subscriptions
GraphQL Subscriptions
• Act as server-side push messages

• Typically via WebSockets (but can be set up with polling in theory)

• Auto refresh themselves and notify the client when changed

• Typically require additional GraphQL endpoint and connection


configuration

• Newest feature of GraphQL (2018) and hence support is all over the map
Defining Subscriptions
type Subscription { Same semantics as
nextMessage: GamePlayMessage queries but they
} are refreshed by
the server
type GamePlayMessage {
gameOver: Boolean (can have input parameters
leaderBoard: [LeaderBoardEntry!]! and return responses)
}

type LeaderBoardEntry {
playerId: String!
nickName: String!
score: Int!
}
Summary of Type Syntax Oddities
• Thing - A Thing. It is not required

• Thing! - A Thing. It is required

• [Thing] - An array of things. The array isn’t required, nor are the individual
entries (which is odd, but a GrapQL-ism)

• [Thing!] - An array of things. The array isn’t required, but if supplied,


each element must be a Thing and not null

• [Thing!]! - A required array of required Things


GraphQL Tools
Schema Mapping Tools
Code Generation - gql-gen
• https://github.com/dotansimha/graphql-code-generator

• Can generate TypeScript, Flow, Java, even integrate to client APIs such as
Apollo

• Can generate a raw Schema AST

• JavaScript functions via resolvers

• Data mappings via servers like Prisma (think data remoting)


Popular GraphQL Distributions

• The official GraphQL reference implementation, graphql-js

• Apollo GraphQL

• Apollo GraphQL Yoga (https://github.com/prisma/yoga2)

• Facebook’s Relay (React-based API for GraphQL) -https://


facebook.github.io/relay/
Lots of other GraphQL APIs
• Clients and servers exist for • C#/.NET

• JavaScript • Go

• Java • Groovy

• Scala • Erlang

• Python • Clojure

• Ruby • Elixr…
GraphiQL Playground
GraphQL Voyager
GraphQL Implementations
• Relay - Facebook’s JS RI
• GraphQL-js - a reference implementation
• Apollo - JavaScript clients and Servers, maintained by Prisma (our focus today)
• Lightweight express-GraphQL, HAPI-GraphQL projects
• Clients/Servers for many other languages / platforms including Java/Spring,
Scala, Clojure, Ruby, Python, PHP, Go, .NET, Elixir, Haskell and more

• Good research on JavaScript clients at https://medium.com/open-graphql/


exploring-different-graphql-clients-d1bc69de305f
You can also post / curl a query…

• Some query tools provide curl examples to the clipboard… (I didn’t type
this in!)

curl 'http:localhost:8080/graphql' -H 'Accept-Encoding: gzip, deflate, br'


-H 'Content-Type: application/json' -H 'Accept: application/json' -H
'Connection: keep-alive' -H 'Origin: altair://-' -H 'Authorization: Bearer
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJrZW5ueSIsImF1dGgiOlt7ImF1dGhvcml0eSI6IlJPT
EVfUExBWUVSIn1dLCJpYXQiOjE1NTYwMTQ1ODksImV4cCI6MTU1NjAxODE4OX0.tFbswqzU5gj
R3jwdlP7yYk21uUN8Lab2xm-orRZPKoQ' --data-binary '{"query":"query {\n \n
gameStatus {\n gameMode\n gameDescription\n currentQuestion {\n
text\n }\n questionScore {\n nickName\n score\n }\n
finalScore\n }\n}","variables":{}}' --compressed
Batteries Not Included
• Things you’ll need to wrestle with

• Security (CORS or Proxy, authentication, authorization)

• Client configuration for subscriptions / web sockets

• Generating client code for schema objects

• Monitoring (Apollo has a potential metrics engine available)

• You need to decide what level of granularity your API will support and you
need to implement each query/mutation/subscription, or delegate it to an API
for processing (like PRISMA)
Compared to JSON

GraphQL REST/JSON

Pros Cons Pros Cons

Query-based APIs difficult for Ubiquitous No standard


newbies query API
Fetch only what Easily tested
you need Config is Metadata models
somewhat Native to SPA also not a
Create types from complex apps standard
schema
Security is a Agnostic to API Subscriptions not
Subscription challenge and tooling native to REST
Model can be non-trivial

Varied API quality


Demonstrations
GraphQL Potential Uses
• Back-end of app with large semantic data structures
• Provide queryable API for customer with their choice of query tool and language
• App-defined ad-hoc or canned queries of content by graph of data
• Push-based messaging can be used on SPA clients

NOTE: GraphQL is not as big of a payoff if data model is trivial


Questions?

Please enter them at


phillyemergingtech.com/qa/

You might also like