SlideShare ist ein Scribd-Unternehmen logo
1 von 60
1BREST
GraphQL
adventures
APRIL 22, 2018
2BREST
ILYA LABACHEUSKI
Software developer in EPAM systems.
Also a member of the IT Shark Community.
The main field is frontend Javascript development. I have some experience in
Node.js and React Native. Some other fields of interest are CAD systems, simple
engineering and some bad habits. :)
ILYA
LABACHEUSKI
EPAM Systems, software developer
3BREST
GraphQL
What is it?
4BREST
GraphQL. What is it?
A query language for your API
Ask for what you need, get exactly that!
{
hero {
aliasName: name
height
mass
}
}
{
"hero": {
"aliasName": "Luke Skywalker",
"height": 1.72,
"mass": 77
}
}
5BREST
This presentation
1. A very simple tutorial for setting up a GraphQL server
written in TypeScript.
2. Some adventures and thoughts about migration to
GraphQL from REST API.
6BREST
Complexity
7BREST
8BREST
Luggage
Persons
Insurance
Flight
Info
Hotel
Car
9BREST
Luggage
Persons
Insurance
Flight
Info
Hotel
Car
Statistics
Emails
AnalyticsA/B
Testing
10BREST
More features,
more data,
more problems
11BREST
Why TypeScript?
12BREST
Simple GraphQL schema
type Airport {
id: number!
name: String!
code: String!
# … more fields
}
type Root {
airport(id: number!): Airport
}
13BREST
Simple query example
type Airport {
id: number!
name: String!
}
type Root {
airport(id: number!): Airport
}
query AirportName($id: number) {
airport($id: id) {
name }
}
14BREST
Vanilla Javascript
const airportName = props => (
<div>Name: {props.graphqlValue.airport.fullName}</div>
)
export default connectGraphQL(DeviceNameComponent, () => ({
query: ...
variables: {
airportId: 123342334
},
}))
15BREST
Possible mistakes
const airportName = props => (
<div>Name: {props.graphqlValue.airport.fullName}</div>
)
export default connectGraphQL(DeviceNameComponent, () => ({
query: ...
variables: {
airportId: 123342334
},
})) Webpack compiles
16BREST
Type it!
type Airport {
id: number!
name: String!
}
type Root {
airport(id: number!): Airport
}
query AirportName($id: number) {
airport($id: id) {
name }
}
interface AirportNameQuery {
airport: {
name: string;
}
}
interface AirportNameInput {
id: number;
}
17BREST
Type it
const airportName = props => (
<div>Name: {props.graphqlValue.airport.fullName}</div>
)
export default connectGraphQL(DeviceNameComponent, () => ({
query: ...
variables: {
airportId: 123342334
},
}))
18BREST
Type it (with TypeScript)
const airportName = (props: Props) => (
<div>Name: {props.graphqlValue.airport.fullName}</div>
)
export default connectGraphQL<Props, AirportNameQuery,
AirportNameInput>(DeviceNameComponent, () => ({
query: ...
variables: {
airportId: 123342334
},
}))
No fullName in type QueryResult
No airportId in type AirportNameInput
19BREST
• Safety — static verification at compile time
• Editor tooling — code help, highlighting, going to definition
• One source of truth — types should have unique reference
Advantages
20BREST
Server setup
21BREST
Good tools to use
• ts-node — the same as node for TypeScript
• tslint + rules — eslint for TypeScript
• express (koa …) — works well with TypeScript
• apollo-server-express — for GraphQL
• graphql-playground-middleware-express — a playground
• graphql-voyager — to see everything graphically
• jest + ts-jest — unit testing
• nodemon — reloading the server
• graphql-import — write in .graphql files
22BREST
GraphQL Playground
23BREST
GraphQL Playground
24BREST
25BREST
Server
import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress } from 'apollo-server-express';
import { schema } from './schema';
const PORT = 3000;
const app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.listen(PORT);
26BREST
Playground and Voyager
import playground from 'graphql-playground-middleware-express';
import { express as voyager } from 'graphql-voyager/middleware';
...
// bodyParser is needed just for POST.
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.get('/graphiql', playground({ endpoint: '/graphql' }));
app.use('/voyager', voyager({ endpointUrl: '/graphql' }));
app.listen(PORT);
27BREST
schema.ts
import { importSchema } from 'graphql-import';
const resolvers = {
Query: {
// ...
},
};
export const schema = makeExecutableSchema({
resolvers,
typeDefs: importSchema('src/schema/root.graphql'),
});
28BREST
root.graphql
# import Flight from 'flight.graphql'
# import Airport from 'airport.graphql'
# Root query description
type Query {
# Simple description
airport(id: ID!): Airport
flight(id: ID!): Flight
}
29BREST
schema.ts
import { importSchema } from 'graphql-import';
export const schema = makeExecutableSchema({
resolvers,
typeDefs: importSchema('src/schema/root.graphql'),
});
Will generate combined AST for your schema:
- root.graphql
| — flight.graphql
| — airport.graphql
| | — importInAirport.graphql
...
30BREST
nodemon settings
{
"ignore": ["**/*.test.ts", "**/*.spec.ts", ".git", "node_modules"],
"watch": ["src"],
"execMap": {
"ts": "./node_modules/.bin/ts-node"
},
"events": {
"start": "./node_modules/.bin/tslint -c ./tslint.json 'src/**/*.ts' --format
stylish --force"
},
"ext": "ts js graphql",
"env": {
"NODE_ENV": "development"}
}
31BREST
Migration
32BREST
Schemifying your REST APIs
• Write by hand?
• Auto generate?
• Do both?
• Do you have full documentation for REST APIs?
• Are all fields in requests and responses defined?
33BREST
Writing a schema manually
Pros:
• GraphQL will be defined for your specific needs.
• Easy to extend, simplify or remove types.
Cons:
• Any update in REST APIs requires attention.
• Requires big analysis of how you use your API.
• The process is long.
34BREST
Auto generation from REST APIs
Pros:
• You can generate a schema from existing REST schemas
(Swagger/OpenAPI) relatively easily.
• You can combine multiple API REST and GraphQL services.
Cons:
• The schema will be more complex.
• Changes in types require a complex tool to generate an updated
schema properly.
35BREST
Combination of both
Pros:
• Automatic translation for basic types.
• Flexibility to make your schema simpler and better.
Cons:
• Your schema will be the source of truth and will not repeat your
REST APIs.
• Still a lot of work.
36BREST
No documentation for REST APIs
What we have done:
- Logged all API requests and their responses to JSON.
- Translated responses in JSON files to TypeScript types.
- Translated TypeScript types to a GraphQL schema.
- Tried to make an automatic script that will repeat all the needed
API calls to make a ‘happy flow.’
37BREST
Logged APIs
[{ "timestamp": 1521795786330,
"id": "b543e0f663d2",
"type": "request",
"payload": {
"url": "https://api.oursite.com/params",
"method": "GET" }
},{
"timestamp": 1521795786691,
"id": "b543e0f663d2",
"type": "response",
"payload": {
"body": { ... },
"status": 200 }
}, ... ]
38BREST
Convert JSON to files
- Initial Loading Requests
| — 01_RootApi_response.ts
| — 02_FlightApi_response.ts
| — 03_PassengersDetailsAPI_response.ts
...
`https://api.oursite.com/87fdg7sdfr9`
`https://api.oursite.com/flight/868`
`https://api.backend.com/passenges/87fdg7sdfr9/details/578d`
39BREST
Typescript files content
// https://api.oursite.com/87fdg7sdfr9
export interface RootApiResponse {
_links: Links;
}
export interface FlightDetails {
href: string;
template: boolean;
}
export interface Links {
self: Self;
"flight:details": FlightDetails;
"passengers:details": FlightDetails;
}
export interface Self { href: string; }
Root API
flight:details passengers:details
airports
car:shop
insurance:details
REST HAL
40BREST
Problems — 1
// https://api.oursite.com/87fdg7sdfr9
export interface RootApiResponse {
_links: Links;
}
export interface FlightDetails {
href: string;
template: boolean;
}
export interface Links {
self: Self;
"flight:details": FlightDetails;
"passengers:details": FlightDetails;
}
export interface Self { href: string; }
Repeated types
41BREST
Problems — 2
// https://api.oursite.com/87fdg7sdfr9
export interface RootApiResponse {
_links: Links;
}
export interface FlightDetails {
href: string;
template: boolean;
}
export interface Links {
self: Self;
"flight:details": FlightDetails;
"passengers:details": FlightDetails;
}
export interface Self { href: string; }
Forbidden symbols in GraphQL
42BREST
Problems — 3
// https://api.oursite.com/87fdg7sdfr9
export interface RootApiResponse {
_links: Links;
}
export interface FlightDetails {
href: string;
template: boolean;
}
export interface Links {
self: Self;
"flight:details": FlightDetails;
"passengers:details": FlightDetails;
}
export interface Self { href: string; }
Merged types
43BREST
Problems — 4
// https://api.oursite.com/87fdg7sdfr9
export interface RootApiResponse {
_links: Links;
}
export interface FlightDetails {
href: string;
template: boolean;
}
export interface Links {
self: Self;
"flight:details": FlightDetails;
"passengers:details": FlightDetails;
}
export interface Self { href: string; }
Names do not express
the semantics.
44BREST
Converting to GraphQL
type RootApiResponse {
_links: Links;
}
type FlightDetails {
href: string;
template: boolean;
}
type Links {
self: Self;
flightDetails: FlightDetails;
passengersDetails: FlightDetails;
}
type Self { href: string; }
45BREST
Simplify and correct schema
type RootApiResponse {
_links: Links!;
}
type Link {
href: string!;
template: boolean;
}
type Links {
self: Link!;
flightDetails: Link!;
passengersDetails: Link!;
}
46BREST
No response — no type
export interface Passengers {
passenger: Passenger;
baggage: Baggage;
}
export interface Baggage {
Items: any[];
}
47BREST
Automatic scripts
import { BaggageResponse } from './05_BaggageApi_response'
import { PassengersResponse } from './02_PassengersAPI_response';
const baggage = await fetchJson<BaggageResponse>(baggageUrl);
const flightPassengersInput = { baggage, person }
const passengersResult = await fetchJson<PassengersResponse>(url, {
body: flightPassengersInput,
});
48BREST
Exposing REST API structure
49BREST
Mimicing REST API vs making GraphQL first
query {
flightResourse {
getPassengers(flightId: ID!) : Passengers
}
}
# vs
query {
getPassengersByFlightId(flightId: ID!) : Passengers
}
Nested structure
Flat structure with many root queries
50BREST
Mimicing REST API
type MutationOnPage {
postPassengers(opts: PassengersInput!): PassengersResponseSubmit
}
Can be a completely unique type.
51BREST
Mimicing REST API: getting your data
type MutationOnPage {
postPassengers(opts: PassengersInput!): PassengersResponseSubmit
}
input PassengersInput {
baggage: [Baggages!]!
Person: Person!
}
input BaggagesInput {
Items: [Baggage!]!
}
Comes from another request, that depends on
another request, that depends… and so one
52BREST
Mimicing REST API forces to make a nested schema
query getInfoForPassengersInput {
getFlight(id: ID!) {
getPassengers {
getBaggage {
...
}}}}
query getInfoForInsuranceInput {
getFlight(id: ID!) {
getServices {
getPassengers {
...
}}}}
For every unique situation you will have its
own nesting with possibly unique types
53BREST
Mimicing REST APIs
Pros:
• Easy to convert
Cons:
• Your schema will be a mess of unique flows and types.
• Getting data is a traversing graph.
54BREST
Making GraphQL first
query getInfoForPassengersInput {
flight(id: ID!) {
passengers { ... }
baggage { ... }
}}}
query getInfoForInsuranceInput {
flight(id: ID!) {
services { ... }
passengers { ... }
}}}
55BREST
Making GraphQL first
query getInfoForPassengersInput {
flight(id: ID!) {
passengers { ... }
baggage { ... }
}}}
const resolvers = {
passengers: ({flightId, serviceId}, opts, ctx) => {
return flightId
? restApiCall('https://api.flights.com/')
: restApiCall('https://api.services.com/')
}
},
},
};
56BREST
GraphQL first
Pros:
• Reuse of types
• Simpler schema and queries
• Simpler for a data client
Cons:
• Resolvers can be very smart.
57BREST
REST APIs with expiration tokens
`https://api.oursite.com/{token}`
query {
flight(id: ID!) { <- 300 ms REST API call
passengers { <- 400 ms REST API call
baggage { <-- here the token expires
}
}
}
}
You should have a strategy what to do in such case.
58BREST
Query complexity
query {
flight(id: ID!) {
carrier
price
}
airport(limit: 20) {
name
city
}
}
flight + carrier + price = 3
In case for every airport is needed separate
REST API request:
(airport + name + city) * 20 = 60
Total = 63
59BREST
THANK YOU
60BREST
CONTACT INFORMATION
Your_mail@epam.c
om
Usernam
e
Usernam
e
Usernam
e
Usernam
e
Ilya Labacheuski ilya.labacheuski@gmail.com
https://github.com/ilabacheuski

Weitere ähnliche Inhalte

Was ist angesagt?

apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...
apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...
apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...apidays
 
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20CodeValue
 
GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018Sashko Stubailo
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHPAndrew Rota
 
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
 
Modular GraphQL with Schema Stitching
Modular GraphQL with Schema StitchingModular GraphQL with Schema Stitching
Modular GraphQL with Schema StitchingSashko Stubailo
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersSashko Stubailo
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architectureSashko Stubailo
 
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern Apps
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern AppsMeteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern Apps
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern AppsSashko Stubailo
 
Cooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal ArchitectureCooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal ArchitectureJeroen Rosenberg
 
Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHPAndrew Rota
 
GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL IntroductionSerge Huber
 
Extending Flink State Serialization for Better Performance and Smaller Checkp...
Extending Flink State Serialization for Better Performance and Smaller Checkp...Extending Flink State Serialization for Better Performance and Smaller Checkp...
Extending Flink State Serialization for Better Performance and Smaller Checkp...Flink Forward
 
No Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in PracticeNo Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in PracticeRocky Neurock
 
The Apollo and GraphQL Stack
The Apollo and GraphQL StackThe Apollo and GraphQL Stack
The Apollo and GraphQL StackSashko Stubailo
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLBrainhub
 
GraphQL is new sexy
GraphQL is new sexyGraphQL is new sexy
GraphQL is new sexyITEM
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaScala Italy
 

Was ist angesagt? (20)

apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...
apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...
apidays LIVE New York 2021 - Introduction to HATEOAS with Ketting by Evert Po...
 
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20
Alon Fliess: APM – What Is It, and Why Do I Need It? - Architecture Next 20
 
GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 
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)
 
Modular GraphQL with Schema Stitching
Modular GraphQL with Schema StitchingModular GraphQL with Schema Stitching
Modular GraphQL with Schema Stitching
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product Developers
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
 
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern Apps
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern AppsMeteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern Apps
Meteor MIT Tech Talk 9/18/14: Designing a New Platform For Modern Apps
 
Cooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal ArchitectureCooking your Ravioli "al dente" with Hexagonal Architecture
Cooking your Ravioli "al dente" with Hexagonal Architecture
 
Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
 
GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL Introduction
 
Extending Flink State Serialization for Better Performance and Smaller Checkp...
Extending Flink State Serialization for Better Performance and Smaller Checkp...Extending Flink State Serialization for Better Performance and Smaller Checkp...
Extending Flink State Serialization for Better Performance and Smaller Checkp...
 
No Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in PracticeNo Graph Theory Required: Ember and GraphQL in Practice
No Graph Theory Required: Ember and GraphQL in Practice
 
Apiary
ApiaryApiary
Apiary
 
Boost your API with GraphQL
Boost your API with GraphQLBoost your API with GraphQL
Boost your API with GraphQL
 
The Apollo and GraphQL Stack
The Apollo and GraphQL StackThe Apollo and GraphQL Stack
The Apollo and GraphQL Stack
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
GraphQL is new sexy
GraphQL is new sexyGraphQL is new sexy
GraphQL is new sexy
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
 

Ähnlich wie SETCON'18 - Ilya labacheuski - GraphQL adventures

GraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer toolsGraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer toolsSashko Stubailo
 
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...apidays
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCTim Burks
 
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolFrom Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolESUG
 
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessYour API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessQAware GmbH
 
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...apidays
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and serverPavel Chertorogov
 
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
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Tugdual Grall
 
Exposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIsExposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIsWSO2
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overviewscdhruv5
 
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019UA DevOps Conference
 
Apex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasApex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasSalesforce Developers
 
StrongLoop Overview
StrongLoop OverviewStrongLoop Overview
StrongLoop OverviewShubhra Kar
 
Seattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp APISeattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp APIshareddatamsft
 
Introduction to GraphQL and AWS Appsync on AWS - iOS
Introduction to GraphQL and AWS Appsync on AWS - iOSIntroduction to GraphQL and AWS Appsync on AWS - iOS
Introduction to GraphQL and AWS Appsync on AWS - iOSAmazon Web Services
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchNikolas Burk
 

Ähnlich wie SETCON'18 - Ilya labacheuski - GraphQL adventures (20)

GraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer toolsGraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer tools
 
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...
apidays LIVE Australia - Have your cake and eat it too: GraphQL? REST? Why no...
 
Implementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPCImplementing OpenAPI and GraphQL services with gRPC
Implementing OpenAPI and GraphQL services with gRPC
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
 
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks ToolFrom Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
From Legacy Database to Domain Layer Using a New Cincom VisualWorks Tool
 
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessYour API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or Serverless
 
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
apidays LIVE Hong Kong 2021 - GraphQL : Beyond APIs, graph your enterprise by...
 
GraphQL the holy contract between client and server
GraphQL the holy contract between client and serverGraphQL the holy contract between client and server
GraphQL the holy contract between client and server
 
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...
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
 
Exposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIsExposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIs
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overview
 
React inter3
React inter3React inter3
React inter3
 
MesosCon - Be a microservices hero
MesosCon - Be a microservices heroMesosCon - Be a microservices hero
MesosCon - Be a microservices hero
 
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019
ОЛЕГ МАЦЬКІВ «Crash course on Operator Framework» Lviv DevOps Conference 2019
 
Apex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and CanvasApex Code Analysis Using the Tooling API and Canvas
Apex Code Analysis Using the Tooling API and Canvas
 
StrongLoop Overview
StrongLoop OverviewStrongLoop Overview
StrongLoop Overview
 
Seattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp APISeattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp API
 
Introduction to GraphQL and AWS Appsync on AWS - iOS
Introduction to GraphQL and AWS Appsync on AWS - iOSIntroduction to GraphQL and AWS Appsync on AWS - iOS
Introduction to GraphQL and AWS Appsync on AWS - iOS
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
 

Mehr von Nadzeya Pus

SETCON'18 - Yauheni Pakala - .NET Embedding
SETCON'18 - Yauheni Pakala - .NET Embedding SETCON'18 - Yauheni Pakala - .NET Embedding
SETCON'18 - Yauheni Pakala - .NET Embedding Nadzeya Pus
 
SETCON'18 - Vitali Fokin - Kubernetes 101
SETCON'18 - Vitali Fokin - Kubernetes 101SETCON'18 - Vitali Fokin - Kubernetes 101
SETCON'18 - Vitali Fokin - Kubernetes 101Nadzeya Pus
 
SETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise OrchestrationSETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise OrchestrationNadzeya Pus
 
SETCON'18 - Siarhei Skavarodkin - Docker for developers
SETCON'18 - Siarhei Skavarodkin - Docker for developersSETCON'18 - Siarhei Skavarodkin - Docker for developers
SETCON'18 - Siarhei Skavarodkin - Docker for developersNadzeya Pus
 
SETCON'18 - Dzmitry Nichyparuk - Designing reliable software
SETCON'18 - Dzmitry Nichyparuk - Designing reliable softwareSETCON'18 - Dzmitry Nichyparuk - Designing reliable software
SETCON'18 - Dzmitry Nichyparuk - Designing reliable softwareNadzeya Pus
 
SETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPUSETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPUNadzeya Pus
 
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы Nadzeya Pus
 

Mehr von Nadzeya Pus (7)

SETCON'18 - Yauheni Pakala - .NET Embedding
SETCON'18 - Yauheni Pakala - .NET Embedding SETCON'18 - Yauheni Pakala - .NET Embedding
SETCON'18 - Yauheni Pakala - .NET Embedding
 
SETCON'18 - Vitali Fokin - Kubernetes 101
SETCON'18 - Vitali Fokin - Kubernetes 101SETCON'18 - Vitali Fokin - Kubernetes 101
SETCON'18 - Vitali Fokin - Kubernetes 101
 
SETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise OrchestrationSETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise Orchestration
 
SETCON'18 - Siarhei Skavarodkin - Docker for developers
SETCON'18 - Siarhei Skavarodkin - Docker for developersSETCON'18 - Siarhei Skavarodkin - Docker for developers
SETCON'18 - Siarhei Skavarodkin - Docker for developers
 
SETCON'18 - Dzmitry Nichyparuk - Designing reliable software
SETCON'18 - Dzmitry Nichyparuk - Designing reliable softwareSETCON'18 - Dzmitry Nichyparuk - Designing reliable software
SETCON'18 - Dzmitry Nichyparuk - Designing reliable software
 
SETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPUSETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPU
 
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы
SETCON'18 - Aleh Toba - Путь из Developer-a в Manager-ы
 

Kürzlich hochgeladen

Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 

Kürzlich hochgeladen (20)

Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 

SETCON'18 - Ilya labacheuski - GraphQL adventures

  • 2. 2BREST ILYA LABACHEUSKI Software developer in EPAM systems. Also a member of the IT Shark Community. The main field is frontend Javascript development. I have some experience in Node.js and React Native. Some other fields of interest are CAD systems, simple engineering and some bad habits. :) ILYA LABACHEUSKI EPAM Systems, software developer
  • 4. 4BREST GraphQL. What is it? A query language for your API Ask for what you need, get exactly that! { hero { aliasName: name height mass } } { "hero": { "aliasName": "Luke Skywalker", "height": 1.72, "mass": 77 } }
  • 5. 5BREST This presentation 1. A very simple tutorial for setting up a GraphQL server written in TypeScript. 2. Some adventures and thoughts about migration to GraphQL from REST API.
  • 12. 12BREST Simple GraphQL schema type Airport { id: number! name: String! code: String! # … more fields } type Root { airport(id: number!): Airport }
  • 13. 13BREST Simple query example type Airport { id: number! name: String! } type Root { airport(id: number!): Airport } query AirportName($id: number) { airport($id: id) { name } }
  • 14. 14BREST Vanilla Javascript const airportName = props => ( <div>Name: {props.graphqlValue.airport.fullName}</div> ) export default connectGraphQL(DeviceNameComponent, () => ({ query: ... variables: { airportId: 123342334 }, }))
  • 15. 15BREST Possible mistakes const airportName = props => ( <div>Name: {props.graphqlValue.airport.fullName}</div> ) export default connectGraphQL(DeviceNameComponent, () => ({ query: ... variables: { airportId: 123342334 }, })) Webpack compiles
  • 16. 16BREST Type it! type Airport { id: number! name: String! } type Root { airport(id: number!): Airport } query AirportName($id: number) { airport($id: id) { name } } interface AirportNameQuery { airport: { name: string; } } interface AirportNameInput { id: number; }
  • 17. 17BREST Type it const airportName = props => ( <div>Name: {props.graphqlValue.airport.fullName}</div> ) export default connectGraphQL(DeviceNameComponent, () => ({ query: ... variables: { airportId: 123342334 }, }))
  • 18. 18BREST Type it (with TypeScript) const airportName = (props: Props) => ( <div>Name: {props.graphqlValue.airport.fullName}</div> ) export default connectGraphQL<Props, AirportNameQuery, AirportNameInput>(DeviceNameComponent, () => ({ query: ... variables: { airportId: 123342334 }, })) No fullName in type QueryResult No airportId in type AirportNameInput
  • 19. 19BREST • Safety — static verification at compile time • Editor tooling — code help, highlighting, going to definition • One source of truth — types should have unique reference Advantages
  • 21. 21BREST Good tools to use • ts-node — the same as node for TypeScript • tslint + rules — eslint for TypeScript • express (koa …) — works well with TypeScript • apollo-server-express — for GraphQL • graphql-playground-middleware-express — a playground • graphql-voyager — to see everything graphically • jest + ts-jest — unit testing • nodemon — reloading the server • graphql-import — write in .graphql files
  • 25. 25BREST Server import express from 'express'; import bodyParser from 'body-parser'; import { graphqlExpress } from 'apollo-server-express'; import { schema } from './schema'; const PORT = 3000; const app = express(); app.use('/graphql', bodyParser.json(), graphqlExpress({ schema })); app.listen(PORT);
  • 26. 26BREST Playground and Voyager import playground from 'graphql-playground-middleware-express'; import { express as voyager } from 'graphql-voyager/middleware'; ... // bodyParser is needed just for POST. app.use('/graphql', bodyParser.json(), graphqlExpress({ schema })); app.get('/graphiql', playground({ endpoint: '/graphql' })); app.use('/voyager', voyager({ endpointUrl: '/graphql' })); app.listen(PORT);
  • 27. 27BREST schema.ts import { importSchema } from 'graphql-import'; const resolvers = { Query: { // ... }, }; export const schema = makeExecutableSchema({ resolvers, typeDefs: importSchema('src/schema/root.graphql'), });
  • 28. 28BREST root.graphql # import Flight from 'flight.graphql' # import Airport from 'airport.graphql' # Root query description type Query { # Simple description airport(id: ID!): Airport flight(id: ID!): Flight }
  • 29. 29BREST schema.ts import { importSchema } from 'graphql-import'; export const schema = makeExecutableSchema({ resolvers, typeDefs: importSchema('src/schema/root.graphql'), }); Will generate combined AST for your schema: - root.graphql | — flight.graphql | — airport.graphql | | — importInAirport.graphql ...
  • 30. 30BREST nodemon settings { "ignore": ["**/*.test.ts", "**/*.spec.ts", ".git", "node_modules"], "watch": ["src"], "execMap": { "ts": "./node_modules/.bin/ts-node" }, "events": { "start": "./node_modules/.bin/tslint -c ./tslint.json 'src/**/*.ts' --format stylish --force" }, "ext": "ts js graphql", "env": { "NODE_ENV": "development"} }
  • 32. 32BREST Schemifying your REST APIs • Write by hand? • Auto generate? • Do both? • Do you have full documentation for REST APIs? • Are all fields in requests and responses defined?
  • 33. 33BREST Writing a schema manually Pros: • GraphQL will be defined for your specific needs. • Easy to extend, simplify or remove types. Cons: • Any update in REST APIs requires attention. • Requires big analysis of how you use your API. • The process is long.
  • 34. 34BREST Auto generation from REST APIs Pros: • You can generate a schema from existing REST schemas (Swagger/OpenAPI) relatively easily. • You can combine multiple API REST and GraphQL services. Cons: • The schema will be more complex. • Changes in types require a complex tool to generate an updated schema properly.
  • 35. 35BREST Combination of both Pros: • Automatic translation for basic types. • Flexibility to make your schema simpler and better. Cons: • Your schema will be the source of truth and will not repeat your REST APIs. • Still a lot of work.
  • 36. 36BREST No documentation for REST APIs What we have done: - Logged all API requests and their responses to JSON. - Translated responses in JSON files to TypeScript types. - Translated TypeScript types to a GraphQL schema. - Tried to make an automatic script that will repeat all the needed API calls to make a ‘happy flow.’
  • 37. 37BREST Logged APIs [{ "timestamp": 1521795786330, "id": "b543e0f663d2", "type": "request", "payload": { "url": "https://api.oursite.com/params", "method": "GET" } },{ "timestamp": 1521795786691, "id": "b543e0f663d2", "type": "response", "payload": { "body": { ... }, "status": 200 } }, ... ]
  • 38. 38BREST Convert JSON to files - Initial Loading Requests | — 01_RootApi_response.ts | — 02_FlightApi_response.ts | — 03_PassengersDetailsAPI_response.ts ... `https://api.oursite.com/87fdg7sdfr9` `https://api.oursite.com/flight/868` `https://api.backend.com/passenges/87fdg7sdfr9/details/578d`
  • 39. 39BREST Typescript files content // https://api.oursite.com/87fdg7sdfr9 export interface RootApiResponse { _links: Links; } export interface FlightDetails { href: string; template: boolean; } export interface Links { self: Self; "flight:details": FlightDetails; "passengers:details": FlightDetails; } export interface Self { href: string; } Root API flight:details passengers:details airports car:shop insurance:details REST HAL
  • 40. 40BREST Problems — 1 // https://api.oursite.com/87fdg7sdfr9 export interface RootApiResponse { _links: Links; } export interface FlightDetails { href: string; template: boolean; } export interface Links { self: Self; "flight:details": FlightDetails; "passengers:details": FlightDetails; } export interface Self { href: string; } Repeated types
  • 41. 41BREST Problems — 2 // https://api.oursite.com/87fdg7sdfr9 export interface RootApiResponse { _links: Links; } export interface FlightDetails { href: string; template: boolean; } export interface Links { self: Self; "flight:details": FlightDetails; "passengers:details": FlightDetails; } export interface Self { href: string; } Forbidden symbols in GraphQL
  • 42. 42BREST Problems — 3 // https://api.oursite.com/87fdg7sdfr9 export interface RootApiResponse { _links: Links; } export interface FlightDetails { href: string; template: boolean; } export interface Links { self: Self; "flight:details": FlightDetails; "passengers:details": FlightDetails; } export interface Self { href: string; } Merged types
  • 43. 43BREST Problems — 4 // https://api.oursite.com/87fdg7sdfr9 export interface RootApiResponse { _links: Links; } export interface FlightDetails { href: string; template: boolean; } export interface Links { self: Self; "flight:details": FlightDetails; "passengers:details": FlightDetails; } export interface Self { href: string; } Names do not express the semantics.
  • 44. 44BREST Converting to GraphQL type RootApiResponse { _links: Links; } type FlightDetails { href: string; template: boolean; } type Links { self: Self; flightDetails: FlightDetails; passengersDetails: FlightDetails; } type Self { href: string; }
  • 45. 45BREST Simplify and correct schema type RootApiResponse { _links: Links!; } type Link { href: string!; template: boolean; } type Links { self: Link!; flightDetails: Link!; passengersDetails: Link!; }
  • 46. 46BREST No response — no type export interface Passengers { passenger: Passenger; baggage: Baggage; } export interface Baggage { Items: any[]; }
  • 47. 47BREST Automatic scripts import { BaggageResponse } from './05_BaggageApi_response' import { PassengersResponse } from './02_PassengersAPI_response'; const baggage = await fetchJson<BaggageResponse>(baggageUrl); const flightPassengersInput = { baggage, person } const passengersResult = await fetchJson<PassengersResponse>(url, { body: flightPassengersInput, });
  • 49. 49BREST Mimicing REST API vs making GraphQL first query { flightResourse { getPassengers(flightId: ID!) : Passengers } } # vs query { getPassengersByFlightId(flightId: ID!) : Passengers } Nested structure Flat structure with many root queries
  • 50. 50BREST Mimicing REST API type MutationOnPage { postPassengers(opts: PassengersInput!): PassengersResponseSubmit } Can be a completely unique type.
  • 51. 51BREST Mimicing REST API: getting your data type MutationOnPage { postPassengers(opts: PassengersInput!): PassengersResponseSubmit } input PassengersInput { baggage: [Baggages!]! Person: Person! } input BaggagesInput { Items: [Baggage!]! } Comes from another request, that depends on another request, that depends… and so one
  • 52. 52BREST Mimicing REST API forces to make a nested schema query getInfoForPassengersInput { getFlight(id: ID!) { getPassengers { getBaggage { ... }}}} query getInfoForInsuranceInput { getFlight(id: ID!) { getServices { getPassengers { ... }}}} For every unique situation you will have its own nesting with possibly unique types
  • 53. 53BREST Mimicing REST APIs Pros: • Easy to convert Cons: • Your schema will be a mess of unique flows and types. • Getting data is a traversing graph.
  • 54. 54BREST Making GraphQL first query getInfoForPassengersInput { flight(id: ID!) { passengers { ... } baggage { ... } }}} query getInfoForInsuranceInput { flight(id: ID!) { services { ... } passengers { ... } }}}
  • 55. 55BREST Making GraphQL first query getInfoForPassengersInput { flight(id: ID!) { passengers { ... } baggage { ... } }}} const resolvers = { passengers: ({flightId, serviceId}, opts, ctx) => { return flightId ? restApiCall('https://api.flights.com/') : restApiCall('https://api.services.com/') } }, }, };
  • 56. 56BREST GraphQL first Pros: • Reuse of types • Simpler schema and queries • Simpler for a data client Cons: • Resolvers can be very smart.
  • 57. 57BREST REST APIs with expiration tokens `https://api.oursite.com/{token}` query { flight(id: ID!) { <- 300 ms REST API call passengers { <- 400 ms REST API call baggage { <-- here the token expires } } } } You should have a strategy what to do in such case.
  • 58. 58BREST Query complexity query { flight(id: ID!) { carrier price } airport(limit: 20) { name city } } flight + carrier + price = 3 In case for every airport is needed separate REST API request: (airport + name + city) * 20 = 60 Total = 63