SlideShare a Scribd company logo
1 of 24
Graph QL
Problems with REST API
GET id -------------------> data
GET id2 -------------------> more data
GET data.id ------------------> even more data
Multiple Round Trips
● In order to descent into the object graph, multiple
round trips to the server are required.
● Critical for Mobile Environment
Over fetching
Unless specifically
designed,
you might receive needless
information
Compatibility and Versioning
http://api.myservice.com/v1/users
http://api.myservice.com/v2/users
http://api.myservice.com/v3/users
.
.
Backend APIs
are storage-centric
Front-end APIs
are product-centric
Graph Application Layer Query Language
(not Storage Query Language)
“A better solution that can replace restful server and mvc framework”
Basically JSON without the values
No custom endpoints
Clients ask exactly what they want
person:{ name:, address: }
Graph QL
● User-defined type system - “schema”
● Server describes what data is available
● Clients describe what data they require
● User-defined data fetching (“how do I get an article”)
● Front end request independent to backend
How Graph QL
Works
GraphQL has a type system
Three main “types” required to get an
endpoint up and running.
1. A type for the model
2. A type for the query
3. A type for the schema
In reality, it is more complex than this.
(forget about it for now)
Our Data
var goldbergs = {
1: {
character: "Beverly Goldberg",
actor: "Wendi McLendon-Covey",
role: "matriarch",
traits: "embarrassing, overprotective",
id: 1
},
2: {
character: "Murray Goldberg",
actor: "Jeff Garlin",
role: "patriarch",
traits: "gruff, lazy",
id: 2
},
3: {
character: "Erica Goldberg",
actor: "Hayley Orrantia",
role: "oldest child",
traits: "rebellious, nonchalant",
id: 3
},
4: {
character: "Barry Goldberg",
actor: "Troy Gentile",
role: "middle child",
traits: "dim-witted, untalented",
id: 4
},
5: {
character: "Adam Goldberg",
actor: "Sean Giambrone",
role: "youngest child",
traits: "geeky, pop-culture obsessed",
id: 5
},
6: {
character: "Albert 'Pops' Solomon",
actor: "George Segal",
role: "grandfather",
traits: "goofy, laid back",
id: 6
}
}
Model Type
Model Type is pretty much a mirror image
of each Goldberg in our goldbergs data
--------->
var goldbergType = new GraphQLObjectType({
name: "Goldberg",
description: "Member of The Goldbergs",
fields: {
character: {
type: GraphQLString,
description: "Name of the character",
},
actor: {
type: GraphQLString,
description: "Actor playing the character",
},
role: {
type: GraphQLString,
description: "Family role"
},
traits: {
type: GraphQLString,
description: "Traits this Goldberg is known for"
},
id: {
type: GraphQLInt,
description: "ID of this Goldberg"
}
}
});
1. Create a new instance of GraphQLObjectType, “Goldberg”
2. Under “fields”: Each “type” indicates the type expected
(e.g. string (GraphQLString) for character, int (GraphInt) for id.)
3. “description” fields are good for self-documentation
Query Type
The query type tells how we will query
our data
var queryType = new GraphQLObjectType({
name: "query",
description: "Goldberg query",
fields: {
goldberg: {
type: goldbergType,
args: {
id: {
type: GraphQLInt
}
},
resolve: function(_, args){
return getGoldberg(args.id)
}
}
}
});
function getGoldberg(id) {
return goldbergs[id]
}
1. Query Type is an instance of GraphQLObjectType, it just serves
a different purpose.
2. Create a new query field called goldberg and set its “type” to the
goldbergType we created earlier. Our new goldberg field will accept
an id as an assignment.
3. When we resolve our query we return the output of a function
getGoldberg()
Schema Type
Schema type combines them all together.
/* creating schema instance */
var schema = new GraphQLSchema({
query: queryType
});
/* serve our schema */
var graphQLServer = express();
graphQLServer.use('/', graphqlHTTP({ schema: schema,
graphiql: true }));
graphQLServer.listen(8080);
console.log("The GraphQL Server is running.")
{
goldberg ( id : 2 ) {
id,
character
}
}
{
“data” : {
“goldberg” : {
“id” : 2,
“character” : “Murray Goldberg”
}
}
Let’s Test
Go to GraphiQL IDE and test it yourself.
(GraphiQL IDE is just like postman of RESTful API for GraphQL)
React and
Redux
Let’s delete the “hello world” from
static/index.html and add a new message
using React in index.js:
| -- app
| -- actions
| -- components
| -- reducers
In the “reducers” folder we’ll create a new
file called reducer.js where we’ll work on
our reducer function.
import React from "react";
import ReactDOM from "react-dom";
const Main = React.createClass({
render: () => {
return (
<div>
<p>hello react!</p>
</div>
)
}
});
ReactDOM.render(
<Main />,
document.getElementById("example")
);
React and
Redux
We’ll be using the Immutable module for
our state so that we can form some good
habits.
Our state has two fields — one to let us
know if we are in the middle of a
query/awaiting a response from the server
and another that contains the response
data.
Next we plug our immutableState into a
reducer function:
import Immutable from "immutable";
const immutableState = Immutable.Map({
fetching: false,
data: Immutable.Map({})
})
--------------------------------------------------
export const queryReducer = (state = immutableState,
action) => {
switch (action.type) {
case "STARTING_REQUEST":
return state.set("fetching", true);
case "FINISHED_REQUEST":
return state.set("fetching", false)
.set("data",
Immutable.Map(action.response.data.goldberg));
default:
return state
}
}
Store
Back in index.js we want to create a store
out of our reducer and feed it to our main
component.
We’ll need to import the reducer we just
created along with some helpers from
redux and react-redux.
We also need the redux-thunk middleware
to help us later on when we need to make
some requests.
import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import { queryReducer } from
"./app/reducers/reducers.js";
import thunkMiddleware from "redux-thunk";
/* First, we apply the redux-thunk middleware:*/
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware
)(createStore)
/* Then we wrap our Main component in the Redux
Provider and pass our queryReducer into
createStoreWithMiddleware.*/
ReactDOM.render(
<Provider
store={createStoreWithMiddleware(queryReducer)}>
<Main />
</Provider>,
document.getElementById("example")
);
Actions
In the “actions” folder we’ll create a new
file called actions.js.
We need to create two actions to dispatch
to our reducer,
one for “STARTING_REQUEST”
and one for “FINISHED_REQUEST”:
const startingRequest = () => {
return {
type: "STARTING_REQUEST"
}
}
const finishedRequest = (response) => {
return {
type: "FINISHED_REQUEST",
response: response
}
}
Actions
The great thing about the redux-thunk
middleware we applied to our store earlier
is that when an action returns a function
that function is injected with dispatch().
We’ll get to use dispatch() twice in a new
action called getGraph:
When getGraph() is called we dispatch
startingRequest() to indicate the start of a
new query. We then begin the async
request (note the “application/graphql”
content type in the header) and when our
query is complete we dispatch
finishedRequest() with the results of our
query.
export const getGraph = (payload) => {
return dispatch => {
dispatch(startingRequest());
return new Promise(function(resolve, reject) {
let request=new XMLHttpRequest();
request.open("POST", "/graphql", true);
request.setRequestHeader("Content-Type",
"application/graphql");
request.send(payload);
request.onreadystatechange = () => {
if (request.readyState === 4) {
resolve(request.responseText)
}
}
}).then(response =>
dispatch(finishedRequest(JSON.parse(response))))
}
}
Component
For now we’ll create an empty Query
component:
We need to hook up our component with
our store and the dispatch method by
creating a container component and using
the react-redux connect() helper.
import React from ‘react’;
import { connect } from ‘react-redux’;
import { getGraph } from ‘../actions/actions.js’;
let Query = React.createClass({
render() {
return (
<div>
</div>
)
}
});
const mapStateToProps = (state) => {
return {
store: state
}
};
export const QueryContainer = connect(
mapStateToProps
)(Query);
let Query = React.createClass({
componentDidMount() {
this.props.dispatch(
getGraph("{goldberg(id: 2) {id, character, actor}}")
);
}
});
Component
We’ll also add the elements that our
response data will fill and a button to
submit additional queries. We want to
know if we are in the middle of a query so
we’ll grab our fetching field from our state
and display it on the page.
let Query = React.createClass({
componentDidMount() {
this.props.dispatch(
getGraph("{goldberg(id: 2) {id, character, actor}}")
);
},
render() {
let dispatch = this.props.dispatch;
let fetchInProgress =
String(this.props.store.get('fetching'));
let queryText;
let goldberg = this.props.store.get('data').toObject();
return (
<div>
<p>Fetch in progress: {fetchInProgress}</p>
<h3>{ goldberg.character }</h3>
<p>{ goldberg.actor }</p>
<p>{ goldberg.role }</p>
<p>{ goldberg.traits }</p>
<input ref={node => {queryText = node}}></input>
<button onClick={() => {
dispatch(getGraph(queryText.value))}
}>
query
</button>
</div>
)
}
});
Component
With that done, the last thing we have to
do is plug our QueryContainer component
into our Main component.
In index.js:
import { QueryContainer } from “./app/components/Query.js”;
// And replace “hello react!”
const Main = () => {
return (
<div>
<QueryContainer />
</div>
)
};
● https://learngraphql.com/basics/introduction
● https://medium.com/@thisbejim/getting-started-with-redux-and-graphql-
8384b3b25c56#.x08ia9y7m
Resources used in this
Presentation
Go to GraphiQL IDE and test it yourself.
(GraphiQL IDE is just like postman of RESTful API for GraphQL)

More Related Content

What's hot

GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016Brad Pillow
 
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)Seven Peaks Speaks
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Rafael Wilber Kerr
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQLvaluebound
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part DeuxBrad Pillow
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQLRodrigo Prates
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQLTaking Control of your Data with GraphQL
Taking Control of your Data with GraphQLVinci Rufus
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architectureSashko Stubailo
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherSashko Stubailo
 

What's hot (20)

GraphQL
GraphQLGraphQL
GraphQL
 
GraphQL IndyJS April 2016
GraphQL IndyJS April 2016GraphQL IndyJS April 2016
GraphQL IndyJS April 2016
 
GraphQL
GraphQLGraphQL
GraphQL
 
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
Graph ql vs rest api - Seven Peaks Software (Node.JS Meetup 18 nov 2021)
 
Intro to GraphQL
 Intro to GraphQL Intro to GraphQL
Intro to GraphQL
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
 
GraphQL & Relay
GraphQL & RelayGraphQL & Relay
GraphQL & Relay
 
GraphQL + relay
GraphQL + relayGraphQL + relay
GraphQL + relay
 
GraphQL With Relay Part Deux
GraphQL With Relay Part DeuxGraphQL With Relay Part Deux
GraphQL With Relay Part Deux
 
Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQLTaking Control of your Data with GraphQL
Taking Control of your Data with GraphQL
 
GraphQL Search
GraphQL SearchGraphQL Search
GraphQL Search
 
Apollo Server
Apollo ServerApollo Server
Apollo Server
 
Graphql
GraphqlGraphql
Graphql
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architectureAdding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits togetherGraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
 

Viewers also liked

[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우NAVER D2
 
Adversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generationAdversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generationKeon Kim
 
개발자라면, 블로그
개발자라면, 블로그개발자라면, 블로그
개발자라면, 블로그HyunSeob Lee
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기raccoony
 
[123] electron 김성훈
[123] electron 김성훈[123] electron 김성훈
[123] electron 김성훈NAVER D2
 
Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법pyrasis
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱NAVER D2
 
Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)Pavel Chertorogov
 
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)Pavel Chertorogov
 
Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning Keon Kim
 
재사용UI 컴포넌트설계
재사용UI 컴포넌트설계재사용UI 컴포넌트설계
재사용UI 컴포넌트설계지수 윤
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflowKeon Kim
 
Front-End 개발의 괜찮은 선택 ES6 & React
Front-End 개발의 괜찮은 선택  ES6 & ReactFront-End 개발의 괜찮은 선택  ES6 & React
Front-End 개발의 괜찮은 선택 ES6 & React지수 윤
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작Taegon Kim
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Kim Hunmin
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔NAVER D2
 
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민NAVER D2
 

Viewers also liked (20)

[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우
 
Adversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generationAdversarial learning for neural dialogue generation
Adversarial learning for neural dialogue generation
 
개발자라면, 블로그
개발자라면, 블로그개발자라면, 블로그
개발자라면, 블로그
 
Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기Docker (Compose) 활용 - 개발 환경 구성하기
Docker (Compose) 활용 - 개발 환경 구성하기
 
[123] electron 김성훈
[123] electron 김성훈[123] electron 김성훈
[123] electron 김성훈
 
Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법Docker란 무엇인가? : Docker 기본 사용법
Docker란 무엇인가? : Docker 기본 사용법
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱
 
React.js workshop
React.js workshopReact.js workshop
React.js workshop
 
OpenNMT
OpenNMTOpenNMT
OpenNMT
 
Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)Бэкенд, фронтенд — всё смешалось (nodkz)
Бэкенд, фронтенд — всё смешалось (nodkz)
 
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
React, GraphQL и Relay - вполне себе нормальный компонентный подход (nodkz)
 
Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning Stock Prediction Using NLP and Deep Learning
Stock Prediction Using NLP and Deep Learning
 
재사용UI 컴포넌트설계
재사용UI 컴포넌트설계재사용UI 컴포넌트설계
재사용UI 컴포넌트설계
 
Attention mechanisms with tensorflow
Attention mechanisms with tensorflowAttention mechanisms with tensorflow
Attention mechanisms with tensorflow
 
역시 Redux
역시 Redux역시 Redux
역시 Redux
 
Front-End 개발의 괜찮은 선택 ES6 & React
Front-End 개발의 괜찮은 선택  ES6 & ReactFront-End 개발의 괜찮은 선택  ES6 & React
Front-End 개발의 괜찮은 선택 ES6 & React
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔
 
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
[125]react로개발자2명이플랫폼4개를서비스하는이야기 심상민
 

Similar to GraphQL, Redux, and React

GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaMarcinStachniuk
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0Tobias Meixner
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerBruce McPherson
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsMihail Gaberov
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Frost
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionVMware Tanzu
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5Martin Kleppe
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"ITGinGer
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platformsAyush Sharma
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Fwdays
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)croquiscom
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in CassandraJairam Chandar
 

Similar to GraphQL, Redux, and React (20)

Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
Wroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in JavaWroclaw GraphQL - GraphQL in Java
Wroclaw GraphQL - GraphQL in Java
 
GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0GraphQL Bangkok Meetup 2.0
GraphQL Bangkok Meetup 2.0
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
MPD2011 | Сергей Клюев "RESTfull iOS with RestKit"
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
 
Splitapp coding
Splitapp codingSplitapp coding
Splitapp coding
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 

Recently uploaded

办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
Company Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxCompany Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxMario
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
ETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxNIMMANAGANTI RAMAKRISHNA
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119APNIC
 
Unidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxUnidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxmibuzondetrabajo
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
TRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxTRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxAndrieCagasanAkio
 

Recently uploaded (11)

办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
Company Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptxCompany Snapshot Theme for Business by Slidesgo.pptx
Company Snapshot Theme for Business by Slidesgo.pptx
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
ETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptxETHICAL HACKING dddddddddddddddfnandni.pptx
ETHICAL HACKING dddddddddddddddfnandni.pptx
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119IP addressing and IPv6, presented by Paul Wilson at IETF 119
IP addressing and IPv6, presented by Paul Wilson at IETF 119
 
Unidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptxUnidad 4 – Redes de ordenadores (en inglés).pptx
Unidad 4 – Redes de ordenadores (en inglés).pptx
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
TRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptxTRENDS Enabling and inhibiting dimensions.pptx
TRENDS Enabling and inhibiting dimensions.pptx
 

GraphQL, Redux, and React

  • 2. Problems with REST API GET id -------------------> data GET id2 -------------------> more data GET data.id ------------------> even more data
  • 3. Multiple Round Trips ● In order to descent into the object graph, multiple round trips to the server are required. ● Critical for Mobile Environment
  • 4. Over fetching Unless specifically designed, you might receive needless information
  • 7. Graph Application Layer Query Language (not Storage Query Language) “A better solution that can replace restful server and mvc framework”
  • 8. Basically JSON without the values No custom endpoints Clients ask exactly what they want person:{ name:, address: } Graph QL
  • 9. ● User-defined type system - “schema” ● Server describes what data is available ● Clients describe what data they require ● User-defined data fetching (“how do I get an article”) ● Front end request independent to backend How Graph QL Works
  • 10. GraphQL has a type system Three main “types” required to get an endpoint up and running. 1. A type for the model 2. A type for the query 3. A type for the schema In reality, it is more complex than this. (forget about it for now)
  • 11. Our Data var goldbergs = { 1: { character: "Beverly Goldberg", actor: "Wendi McLendon-Covey", role: "matriarch", traits: "embarrassing, overprotective", id: 1 }, 2: { character: "Murray Goldberg", actor: "Jeff Garlin", role: "patriarch", traits: "gruff, lazy", id: 2 }, 3: { character: "Erica Goldberg", actor: "Hayley Orrantia", role: "oldest child", traits: "rebellious, nonchalant", id: 3 }, 4: { character: "Barry Goldberg", actor: "Troy Gentile", role: "middle child", traits: "dim-witted, untalented", id: 4 }, 5: { character: "Adam Goldberg", actor: "Sean Giambrone", role: "youngest child", traits: "geeky, pop-culture obsessed", id: 5 }, 6: { character: "Albert 'Pops' Solomon", actor: "George Segal", role: "grandfather", traits: "goofy, laid back", id: 6 } }
  • 12. Model Type Model Type is pretty much a mirror image of each Goldberg in our goldbergs data ---------> var goldbergType = new GraphQLObjectType({ name: "Goldberg", description: "Member of The Goldbergs", fields: { character: { type: GraphQLString, description: "Name of the character", }, actor: { type: GraphQLString, description: "Actor playing the character", }, role: { type: GraphQLString, description: "Family role" }, traits: { type: GraphQLString, description: "Traits this Goldberg is known for" }, id: { type: GraphQLInt, description: "ID of this Goldberg" } } }); 1. Create a new instance of GraphQLObjectType, “Goldberg” 2. Under “fields”: Each “type” indicates the type expected (e.g. string (GraphQLString) for character, int (GraphInt) for id.) 3. “description” fields are good for self-documentation
  • 13. Query Type The query type tells how we will query our data var queryType = new GraphQLObjectType({ name: "query", description: "Goldberg query", fields: { goldberg: { type: goldbergType, args: { id: { type: GraphQLInt } }, resolve: function(_, args){ return getGoldberg(args.id) } } } }); function getGoldberg(id) { return goldbergs[id] } 1. Query Type is an instance of GraphQLObjectType, it just serves a different purpose. 2. Create a new query field called goldberg and set its “type” to the goldbergType we created earlier. Our new goldberg field will accept an id as an assignment. 3. When we resolve our query we return the output of a function getGoldberg()
  • 14. Schema Type Schema type combines them all together. /* creating schema instance */ var schema = new GraphQLSchema({ query: queryType }); /* serve our schema */ var graphQLServer = express(); graphQLServer.use('/', graphqlHTTP({ schema: schema, graphiql: true })); graphQLServer.listen(8080); console.log("The GraphQL Server is running.")
  • 15. { goldberg ( id : 2 ) { id, character } } { “data” : { “goldberg” : { “id” : 2, “character” : “Murray Goldberg” } } Let’s Test Go to GraphiQL IDE and test it yourself. (GraphiQL IDE is just like postman of RESTful API for GraphQL)
  • 16. React and Redux Let’s delete the “hello world” from static/index.html and add a new message using React in index.js: | -- app | -- actions | -- components | -- reducers In the “reducers” folder we’ll create a new file called reducer.js where we’ll work on our reducer function. import React from "react"; import ReactDOM from "react-dom"; const Main = React.createClass({ render: () => { return ( <div> <p>hello react!</p> </div> ) } }); ReactDOM.render( <Main />, document.getElementById("example") );
  • 17. React and Redux We’ll be using the Immutable module for our state so that we can form some good habits. Our state has two fields — one to let us know if we are in the middle of a query/awaiting a response from the server and another that contains the response data. Next we plug our immutableState into a reducer function: import Immutable from "immutable"; const immutableState = Immutable.Map({ fetching: false, data: Immutable.Map({}) }) -------------------------------------------------- export const queryReducer = (state = immutableState, action) => { switch (action.type) { case "STARTING_REQUEST": return state.set("fetching", true); case "FINISHED_REQUEST": return state.set("fetching", false) .set("data", Immutable.Map(action.response.data.goldberg)); default: return state } }
  • 18. Store Back in index.js we want to create a store out of our reducer and feed it to our main component. We’ll need to import the reducer we just created along with some helpers from redux and react-redux. We also need the redux-thunk middleware to help us later on when we need to make some requests. import React from "react"; import ReactDOM from "react-dom"; import { createStore, applyMiddleware } from "redux"; import { Provider } from "react-redux"; import { queryReducer } from "./app/reducers/reducers.js"; import thunkMiddleware from "redux-thunk"; /* First, we apply the redux-thunk middleware:*/ const createStoreWithMiddleware = applyMiddleware( thunkMiddleware )(createStore) /* Then we wrap our Main component in the Redux Provider and pass our queryReducer into createStoreWithMiddleware.*/ ReactDOM.render( <Provider store={createStoreWithMiddleware(queryReducer)}> <Main /> </Provider>, document.getElementById("example") );
  • 19. Actions In the “actions” folder we’ll create a new file called actions.js. We need to create two actions to dispatch to our reducer, one for “STARTING_REQUEST” and one for “FINISHED_REQUEST”: const startingRequest = () => { return { type: "STARTING_REQUEST" } } const finishedRequest = (response) => { return { type: "FINISHED_REQUEST", response: response } }
  • 20. Actions The great thing about the redux-thunk middleware we applied to our store earlier is that when an action returns a function that function is injected with dispatch(). We’ll get to use dispatch() twice in a new action called getGraph: When getGraph() is called we dispatch startingRequest() to indicate the start of a new query. We then begin the async request (note the “application/graphql” content type in the header) and when our query is complete we dispatch finishedRequest() with the results of our query. export const getGraph = (payload) => { return dispatch => { dispatch(startingRequest()); return new Promise(function(resolve, reject) { let request=new XMLHttpRequest(); request.open("POST", "/graphql", true); request.setRequestHeader("Content-Type", "application/graphql"); request.send(payload); request.onreadystatechange = () => { if (request.readyState === 4) { resolve(request.responseText) } } }).then(response => dispatch(finishedRequest(JSON.parse(response)))) } }
  • 21. Component For now we’ll create an empty Query component: We need to hook up our component with our store and the dispatch method by creating a container component and using the react-redux connect() helper. import React from ‘react’; import { connect } from ‘react-redux’; import { getGraph } from ‘../actions/actions.js’; let Query = React.createClass({ render() { return ( <div> </div> ) } }); const mapStateToProps = (state) => { return { store: state } }; export const QueryContainer = connect( mapStateToProps )(Query); let Query = React.createClass({ componentDidMount() { this.props.dispatch( getGraph("{goldberg(id: 2) {id, character, actor}}") ); } });
  • 22. Component We’ll also add the elements that our response data will fill and a button to submit additional queries. We want to know if we are in the middle of a query so we’ll grab our fetching field from our state and display it on the page. let Query = React.createClass({ componentDidMount() { this.props.dispatch( getGraph("{goldberg(id: 2) {id, character, actor}}") ); }, render() { let dispatch = this.props.dispatch; let fetchInProgress = String(this.props.store.get('fetching')); let queryText; let goldberg = this.props.store.get('data').toObject(); return ( <div> <p>Fetch in progress: {fetchInProgress}</p> <h3>{ goldberg.character }</h3> <p>{ goldberg.actor }</p> <p>{ goldberg.role }</p> <p>{ goldberg.traits }</p> <input ref={node => {queryText = node}}></input> <button onClick={() => { dispatch(getGraph(queryText.value))} }> query </button> </div> ) } });
  • 23. Component With that done, the last thing we have to do is plug our QueryContainer component into our Main component. In index.js: import { QueryContainer } from “./app/components/Query.js”; // And replace “hello react!” const Main = () => { return ( <div> <QueryContainer /> </div> ) };
  • 24. ● https://learngraphql.com/basics/introduction ● https://medium.com/@thisbejim/getting-started-with-redux-and-graphql- 8384b3b25c56#.x08ia9y7m Resources used in this Presentation Go to GraphiQL IDE and test it yourself. (GraphiQL IDE is just like postman of RESTful API for GraphQL)