SlideShare a Scribd company logo
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

More Related Content

What's hot

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 20
CodeValue
 
GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018GraphQL over REST at Reactathon 2018
GraphQL over REST at Reactathon 2018
Sashko Stubailo
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
Andrew 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 Stitching
Sashko Stubailo
 
Serverless GraphQL for Product Developers
Serverless GraphQL for Product DevelopersServerless GraphQL for Product Developers
Serverless GraphQL for Product Developers
Sashko Stubailo
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
Sashko 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 Apps
Sashko 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 Architecture
Jeroen Rosenberg
 
Getting Started with GraphQL && PHP
Getting Started with GraphQL && PHPGetting Started with GraphQL && PHP
Getting Started with GraphQL && PHP
Andrew Rota
 
GraphQL Introduction
GraphQL IntroductionGraphQL Introduction
GraphQL Introduction
Serge 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 Practice
Rocky Neurock
 
Apiary
ApiaryApiary
Apiary
Suresh B
 
Boost your API with GraphQL
Boost your API with GraphQLBoost your API with GraphQL
Boost your API with GraphQL
Jean-Francois James
 
The Apollo and GraphQL Stack
The Apollo and GraphQL StackThe Apollo and GraphQL Stack
The Apollo and GraphQL Stack
Sashko Stubailo
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Brainhub
 
GraphQL is new sexy
GraphQL is new sexyGraphQL is new sexy
GraphQL is new sexy
ITEM
 
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
Scala Italy
 

What's hot (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
 

Similar to 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 tools
Sashko Stubailo
 
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
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 gRPC
Tim Burks
 
Graphql usage
Graphql usageGraphql usage
Graphql usage
Valentin Buryakov
 
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
ESUG
 
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
QAware 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 server
Pavel 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 2007
Tugdual Grall
 
Exposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIsExposing GraphQLs as Managed APIs
Exposing GraphQLs as Managed APIs
WSO2
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overviewscdhruv5
 
React inter3
React inter3React inter3
React inter3
Oswald Campesato
 
MesosCon - Be a microservices hero
MesosCon - Be a microservices heroMesosCon - Be a microservices hero
MesosCon - Be a microservices hero
Dragos Dascalita Haut
 
ОЛЕГ МАЦЬКІВ «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
UA 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 Canvas
Salesforce Developers
 
StrongLoop Overview
StrongLoop OverviewStrongLoop Overview
StrongLoop Overview
Shubhra Kar
 
Seattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp APISeattle Spark Meetup Mobius CSharp API
Seattle Spark Meetup Mobius CSharp API
shareddatamsft
 
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
Amazon Web Services
 
GraphQL & Prisma from Scratch
GraphQL & Prisma from ScratchGraphQL & Prisma from Scratch
GraphQL & Prisma from Scratch
Nikolas Burk
 

Similar to 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 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
 
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
 

More from 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 101
Nadzeya Pus
 
SETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise OrchestrationSETCON'18 - Siarhei Tuzik - Enterprise Orchestration
SETCON'18 - Siarhei Tuzik - Enterprise Orchestration
Nadzeya 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 developers
Nadzeya 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 software
Nadzeya Pus
 
SETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPUSETCON'18 - Aliaksander Stsepaniuk - Effective CPU
SETCON'18 - Aliaksander Stsepaniuk - Effective CPU
Nadzeya 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
 

More from 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-ы
 

Recently uploaded

addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
ssuser9bd3ba
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 

Recently uploaded (20)

addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 

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