SlideShare uma empresa Scribd logo
1 de 30
GraphQL
A query language for your API
간단하게 알아보는
이기동.
GraphQL?
Graph QL
SQL 비슷하다고 우선 생각하면 됨.
사전적으로 이렇게 생긴걸 Graph라고 함.
# excel chart 생각하면 안됨.
서로 관계가 있는 2개 또는 그 이상의 양의 상태값을 나타낸 도형
누가 만들었지?
Facebook
2012년부터 내부적으로 사용하다 2015년 공개.
언제 만들었지?
Facebook(https://developers.facebook.com/docs/graph-api/using-graph-api)
Github(https://developer.github.com/) v4 api
- Query 해보기(GraphiQL) : https://developer.github.com/v4/explorer/
어디서 쓰고 있어?
스펙이라서 구현을 하던지 언어별로 구현체가 있으니 가져다 쓰면 됨.
http://graphql.org/code/
어떤 언어로 되어 있어?
Why Github using GraphQL
• 모든 Rest API를 제공하고 있지만 gw(integrators)의 요청
을 유연하게 처리하기 힘들었다.
• 때때로 response를 위해 2, 3번의 호출이 필요했다.
• 매개 변수에 대한 검증이 필요했다.
• 코드를 통해 문서를 생성하길 원했다.
• 요청 받을 Response에 대해서 요청자가 정의하길 원한다.
-> 이건 넣고 이건 빼고 할필요 없음. 요청자가 요청한 정보만 내려온다.(=overfetch 방지)
-> GraphiQL을 쓰면 schema 문서가 생성된다.
-> 매개변수에 대한 검증도 FE의 요청쿼리에 대한 validation 가능하다. eslint-plugin-graphql
-> GraphQL이 알아서 해준다.
-> GraphQL을 쓰면 신경 안써도 된다. 스키마만 업데이트 해주면 된다.
https://githubengineering.com/the-github-graphql-api/
– Github 개발팀.
“그래서 GraphQL”
이제 알아보자~
Rest API vs GraphQL
Endpoint 비교
▪ 리스트 조회 : GET /api/posts
▪ 조회 : GET /api/posts/1
▪ 생성 : POST /api/posts
▪ 치환(수정) : PUT or PATCH /api/posts/1
▪ 삭제 : DELETE /api/posts/1
Rest API
▪ 조회, 생성, 수정, 삭제 : POST /graphqlGraphQL
간단하게 oracle/mysql의 console에 붙어서 쿼리 날린다고 생각하자.
그러고 GraphQL 서버에서 할수 있는 쿼리의 스펙을 미리 만들어놓았다 생각
하자.
SQL에 따라서
입력을
조회를
수정을
삭제를
있다.
# 라임 좀 넣었습니다.
GraphQL Server가
할일
node(Schema) 정의.
node 간의 관계도 정의 해주어야 연결이 되겠죠.
연결의 힘을 발휘하기 위해선.
GraphQL은 스펙이고 language 별로 GraphQL 구현체 들이 있으니 구현도 해야겠죠.
expressGraphQL이 제일 많이 쓰는것 같고 쿵짝이 잘 맞는거 같아요.
GraphQL 끼워넣기. #1
GraphQL서버
외부 연동 서버
DB
POST /graphql
GraphQL 끼워넣기 #2
GraphQL서버
인증서버
상품서버
외부서버
기존 Rest API
내부서버
POST /graphql
DB
지양(/graphql 단일 endpoint 지향)
bypass
회사와 사람
코드로 두 node(Entity)로 관계를 지어보자.
샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
회사와 사람
const UserType = new GraphQLObjectType({
name: 'User', // GraphQL Object Name(필수)
fields: () => ({
id: {type: GraphQLString},
firstName: {type: GraphQLString},
age: {type: GraphQLInt},
companyId: {type: GraphQLString},
company: {
type: CompanyType,
resolve(parentValue, args) {
console.log(parentValue, args);
return axios.get(`${SERVER_DOMAIN}/companies/${parentValue.companyId}`)
.then(req => req.data);
}
}
})
});
#사람이 먼저다.
연결(user -> company)
회사와 사람
const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: () => ({
id: {type: GraphQLString},
name: {type: GraphQLString},
description: {type: GraphQLString},
users: {
type: new GraphQLList(UserType),
resolve(parentValue, args) {
return axios.get(`${SERVER_DOMAIN}/companies/${parentValue.id}/users`)
.then(req => req.data);
}
}
})
});
연결(company -> users)
RootQuery
Query(조회) 시 시작될 수 있는 node 를 지정하여야 한다.
따라서 Entity product는 RootQuery에 없으므로 user, company의 field로만 접근 할 수 있다.
RootQuery 지정
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: () => ( {
user: {
type: UserType,
args: {id: {type: GraphQLString}},
resolve(parentValue, args) {
return axios.get(`${SERVER_DOMAIN}/users/${args.id}`)
.then(req => req.data);
}
},
company: {
type: CompanyType,
args: {id: {type: GraphQLString}},
resolve(parentValue, args) {
return axios.get(`${SERVER_DOMAIN}/companies/${args.id}`)
.then(req => req.data);
}
}
})
});
이제 호출해보자.
GraphiQL
작성한 Schema를 보고
Query를 작성하고
유효성을 검사하면서
테스트를 할 수 있는
good dev tool
설치버전도 있고,
서버 띄울때 함께 띄울수 있다.
샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
{
user(id: "23") {
id
firstName
company {
name
}
}
}
{
"data": {
"user": {
"id": "23",
"firstName": "ko",
"company": {
"name": "tomorrow"
}
}
}
}
User정보와 회사정보를 가져오는 샘플
{
company(id: "1") {
id
name
description
users {
id
firstName
age
}
}
}
{
"data": {
"company": {
"id": "1",
"name": "tomorrow",
"description": "111st",
"users": [
{
"id": "23",
"firstName": "ko",
"age": 20
},
{
"id": "40",
"firstName": "lee",
"age": 40
},
{
"id": "44",
"firstName": "ra",
"age": 45
}
]
}
}
}
Company정보와 users를 가져오는 샘플
Mutation
변경작업(추가, 수정, 삭제)
Response Type에 따라서 Query를 원하는대로 데이타를 받을 수도 있다.
Mutation - User 추가
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: UserType,
args: {
firstName: {type: new GraphQLNonNull(GraphQLString)},
age: {type: new GraphQLNonNull(GraphQLInt)},
companyId: {type: GraphQLString}
},
resolve(parentValue, {firstName, age}) {
return axios.post(`${SERVER_DOMAIN}/users`, {firstName, age})
.then(res => res.data);
}
},
deleteUser: {…},
editUser: {…}
}
})
mutation {
addUser(
firstName: “gu",
age: 40
) {
id
firstName
age
}
}
{
"data": {
"addUser": {
"id": "SJ0Wox-i-",
"firstName": "gu",
"age": 40
}
}
}
mutation을 이용한 유저 추가 및 생성 정보 받기
Mutation - User 삭제
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {…},
deleteUser: {
type: UserType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
resolve(parentValue, {id}) {
return axios.delete(`${SERVER_DOMAIN}/users/${id}`)
.then(res => res.data);
}
},
editUser: {…}
}
})
mutation {
deleteUser(
id : "SJ0Wox-i-"
) {
id
}
}
{
"data": {
"deleteUser": {
"id": null
}
}
}
mutation을 이용한 유저 삭제
Mutation - User 수정
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {…},
deleteUser: {…},
editUser: {
type: UserType,
args: {
id: {type: new GraphQLNonNull(GraphQLString)},
firstName: {type: GraphQLString},
age: {type: GraphQLInt},
companyId: {type: GraphQLString}
},
resolve(parentValue, args) {
return axios.patch(`${SERVER_DOMAIN}/users/${args.id}`, args)
.then(res => res.data);
}
}
}
})
mutation {
editUser(
id: "44",
firstName: "ra",
age: 45
) {
id
firstName
age
company {
id
name,
description
}
}
}
{
"data": {
"editUser": {
"id": "44",
"firstName": "ra",
"age": 45,
"company": {
"id": "1",
"name": "tomorrow",
"description": "111st"
}
}
}
}
mutation을 이용한 유저 수정(Patch)
FrontEnd Client 3총사
• Apollo client(http://dev.apollodata.com/)
- All in one
• relay(https://facebook.github.io/relay/)
- performance
• Lokka(https://github.com/kadirahq/lokka)
- Simple
URL
• slide 예제소스.(https://github.com/gidong-lee/graphQL_exam)
- 예제쿼리, 소스, 동작방법등 기술.
• GraphiQL(https://github.com/graphql/graphiql)
• udemy 강의 추천(https://www.udemy.com/graphql-with-react-course)
- 영어가 힘드시면 저처럼 크롬으로 강의 한글번역해서 보시면 보기 편합
니다.
- 크롬으로 강의시작 -> 자막 on(영문) -> 한글로 번역 -> 나쁘지않게 번역
됨.
• graphql query check eslint
(https://github.com/apollographql/eslint-plugin-graphql)
FIN

Mais conteúdo relacionado

Mais procurados

[213]monitoringwithscouter 이건희
[213]monitoringwithscouter 이건희[213]monitoringwithscouter 이건희
[213]monitoringwithscouter 이건희NAVER D2
 
React 튜토리얼 1차시
React 튜토리얼 1차시React 튜토리얼 1차시
React 튜토리얼 1차시태현 김
 
React 튜토리얼 2차시
React 튜토리얼 2차시React 튜토리얼 2차시
React 튜토리얼 2차시태현 김
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작Taegon Kim
 
비전공자의 자바스크립트 도전기
비전공자의 자바스크립트 도전기비전공자의 자바스크립트 도전기
비전공자의 자바스크립트 도전기jeong seok yang
 
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합NAVER D2
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.jsWoo Jin Kim
 
Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Jay Park
 
[하코사 세미나] 비전공자의 자바스크립트 도전기
[하코사 세미나] 비전공자의 자바스크립트 도전기 [하코사 세미나] 비전공자의 자바스크립트 도전기
[하코사 세미나] 비전공자의 자바스크립트 도전기 인권 김
 
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발정석 양
 
Parse.com 맛보기
Parse.com 맛보기Parse.com 맛보기
Parse.com 맛보기flashscope
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게Sungju Jin
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVCArawn Park
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기현철 조
 
[246] foursquare데이터라이프사이클 설현준
[246] foursquare데이터라이프사이클 설현준[246] foursquare데이터라이프사이클 설현준
[246] foursquare데이터라이프사이클 설현준NAVER D2
 
다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!우영 주
 
spring.io를 통해 배우는 spring 개발사례
spring.io를 통해 배우는 spring 개발사례spring.io를 통해 배우는 spring 개발사례
spring.io를 통해 배우는 spring 개발사례Daehwan Lee
 
03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)Hankyo
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XpressEngine
 

Mais procurados (20)

[213]monitoringwithscouter 이건희
[213]monitoringwithscouter 이건희[213]monitoringwithscouter 이건희
[213]monitoringwithscouter 이건희
 
React 튜토리얼 1차시
React 튜토리얼 1차시React 튜토리얼 1차시
React 튜토리얼 1차시
 
React 튜토리얼 2차시
React 튜토리얼 2차시React 튜토리얼 2차시
React 튜토리얼 2차시
 
React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작React Native를 사용한
 초간단 커뮤니티 앱 제작
React Native를 사용한
 초간단 커뮤니티 앱 제작
 
Express 프레임워크
Express 프레임워크Express 프레임워크
Express 프레임워크
 
비전공자의 자바스크립트 도전기
비전공자의 자바스크립트 도전기비전공자의 자바스크립트 도전기
비전공자의 자바스크립트 도전기
 
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.js
 
Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발
 
[하코사 세미나] 비전공자의 자바스크립트 도전기
[하코사 세미나] 비전공자의 자바스크립트 도전기 [하코사 세미나] 비전공자의 자바스크립트 도전기
[하코사 세미나] 비전공자의 자바스크립트 도전기
 
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
 
Parse.com 맛보기
Parse.com 맛보기Parse.com 맛보기
Parse.com 맛보기
 
반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게반복적인 작업이 싫은 안드로이드 개발자에게
반복적인 작업이 싫은 안드로이드 개발자에게
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVC
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
[246] foursquare데이터라이프사이클 설현준
[246] foursquare데이터라이프사이클 설현준[246] foursquare데이터라이프사이클 설현준
[246] foursquare데이터라이프사이클 설현준
 
다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!다함께, FluxUtils 한바퀴!
다함께, FluxUtils 한바퀴!
 
spring.io를 통해 배우는 spring 개발사례
spring.io를 통해 배우는 spring 개발사례spring.io를 통해 배우는 spring 개발사례
spring.io를 통해 배우는 spring 개발사례
 
03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
 

Semelhante a GraphQL overview

Hello, GraphQL!
Hello, GraphQL!Hello, GraphQL!
Hello, GraphQL!민환 조
 
Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015sung yong jung
 
KCSE 2015 Tutorial 빅데이터 분석 기술의 소프트웨어 공학 분야 활용 (...
KCSE 2015 Tutorial 빅데이터 분석 기술의  소프트웨어 공학 분야 활용 (...KCSE 2015 Tutorial 빅데이터 분석 기술의  소프트웨어 공학 분야 활용 (...
KCSE 2015 Tutorial 빅데이터 분석 기술의 소프트웨어 공학 분야 활용 (...Chanjin Park
 
Open source engineering - 0.1
Open source engineering - 0.1Open source engineering - 0.1
Open source engineering - 0.1YoungSu Son
 
Domain Specific Languages With Groovy
Domain Specific Languages With GroovyDomain Specific Languages With Groovy
Domain Specific Languages With GroovyTommy C. Kang
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱NAVER D2
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10흥배 최
 
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End우현 김
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원탑크리에듀(구로디지털단지역3번출구 2분거리)
 
[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우NAVER D2
 
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발Hyunmin Kim
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄SeongHyun Ahn
 
[C언어]함수오버로딩과오버라이딩
[C언어]함수오버로딩과오버라이딩[C언어]함수오버로딩과오버라이딩
[C언어]함수오버로딩과오버라이딩jusingame
 
Java 8 & Beyond
Java 8 & BeyondJava 8 & Beyond
Java 8 & BeyondJay Lee
 
Java8 & Lambda
Java8 & LambdaJava8 & Lambda
Java8 & Lambda기현 황
 
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)r-kor
 
Scala, Scalability
Scala, ScalabilityScala, Scalability
Scala, ScalabilityDongwook Lee
 

Semelhante a GraphQL overview (20)

Hello, GraphQL!
Hello, GraphQL!Hello, GraphQL!
Hello, GraphQL!
 
Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015Isomorphicspring Isomorphic - spring web seminar 2015
Isomorphicspring Isomorphic - spring web seminar 2015
 
KCSE 2015 Tutorial 빅데이터 분석 기술의 소프트웨어 공학 분야 활용 (...
KCSE 2015 Tutorial 빅데이터 분석 기술의  소프트웨어 공학 분야 활용 (...KCSE 2015 Tutorial 빅데이터 분석 기술의  소프트웨어 공학 분야 활용 (...
KCSE 2015 Tutorial 빅데이터 분석 기술의 소프트웨어 공학 분야 활용 (...
 
Open source engineering - 0.1
Open source engineering - 0.1Open source engineering - 0.1
Open source engineering - 0.1
 
Domain Specific Languages With Groovy
Domain Specific Languages With GroovyDomain Specific Languages With Groovy
Domain Specific Languages With Groovy
 
[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱[114]angularvs react 김훈민손찬욱
[114]angularvs react 김훈민손찬욱
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
 
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
 
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
 
[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우[112]rest에서 graph ql과 relay로 갈아타기 이정우
[112]rest에서 graph ql과 relay로 갈아타기 이정우
 
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발
AWS Amplify, AppSync를 이용한 모던 어플리케이션 개발
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄
 
[C언어]함수오버로딩과오버라이딩
[C언어]함수오버로딩과오버라이딩[C언어]함수오버로딩과오버라이딩
[C언어]함수오버로딩과오버라이딩
 
Java 8 & Beyond
Java 8 & BeyondJava 8 & Beyond
Java 8 & Beyond
 
PostGIS 시작하기
PostGIS 시작하기PostGIS 시작하기
PostGIS 시작하기
 
Java8 & Lambda
Java8 & LambdaJava8 & Lambda
Java8 & Lambda
 
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)
RUCK 2017 R로 API 서버를 만드는 4가지 방법(은 삽질기)
 
GraphQL
GraphQLGraphQL
GraphQL
 
Scala, Scalability
Scala, ScalabilityScala, Scalability
Scala, Scalability
 
Scalability
ScalabilityScalability
Scalability
 

GraphQL overview

  • 1. GraphQL A query language for your API 간단하게 알아보는 이기동.
  • 2. GraphQL? Graph QL SQL 비슷하다고 우선 생각하면 됨. 사전적으로 이렇게 생긴걸 Graph라고 함. # excel chart 생각하면 안됨. 서로 관계가 있는 2개 또는 그 이상의 양의 상태값을 나타낸 도형
  • 3. 누가 만들었지? Facebook 2012년부터 내부적으로 사용하다 2015년 공개. 언제 만들었지? Facebook(https://developers.facebook.com/docs/graph-api/using-graph-api) Github(https://developer.github.com/) v4 api - Query 해보기(GraphiQL) : https://developer.github.com/v4/explorer/ 어디서 쓰고 있어? 스펙이라서 구현을 하던지 언어별로 구현체가 있으니 가져다 쓰면 됨. http://graphql.org/code/ 어떤 언어로 되어 있어?
  • 4. Why Github using GraphQL • 모든 Rest API를 제공하고 있지만 gw(integrators)의 요청 을 유연하게 처리하기 힘들었다. • 때때로 response를 위해 2, 3번의 호출이 필요했다. • 매개 변수에 대한 검증이 필요했다. • 코드를 통해 문서를 생성하길 원했다. • 요청 받을 Response에 대해서 요청자가 정의하길 원한다. -> 이건 넣고 이건 빼고 할필요 없음. 요청자가 요청한 정보만 내려온다.(=overfetch 방지) -> GraphiQL을 쓰면 schema 문서가 생성된다. -> 매개변수에 대한 검증도 FE의 요청쿼리에 대한 validation 가능하다. eslint-plugin-graphql -> GraphQL이 알아서 해준다. -> GraphQL을 쓰면 신경 안써도 된다. 스키마만 업데이트 해주면 된다. https://githubengineering.com/the-github-graphql-api/
  • 7. Rest API vs GraphQL Endpoint 비교 ▪ 리스트 조회 : GET /api/posts ▪ 조회 : GET /api/posts/1 ▪ 생성 : POST /api/posts ▪ 치환(수정) : PUT or PATCH /api/posts/1 ▪ 삭제 : DELETE /api/posts/1 Rest API ▪ 조회, 생성, 수정, 삭제 : POST /graphqlGraphQL
  • 8. 간단하게 oracle/mysql의 console에 붙어서 쿼리 날린다고 생각하자. 그러고 GraphQL 서버에서 할수 있는 쿼리의 스펙을 미리 만들어놓았다 생각 하자. SQL에 따라서 입력을 조회를 수정을 삭제를 있다. # 라임 좀 넣었습니다.
  • 10. node(Schema) 정의. node 간의 관계도 정의 해주어야 연결이 되겠죠. 연결의 힘을 발휘하기 위해선. GraphQL은 스펙이고 language 별로 GraphQL 구현체 들이 있으니 구현도 해야겠죠. expressGraphQL이 제일 많이 쓰는것 같고 쿵짝이 잘 맞는거 같아요.
  • 11. GraphQL 끼워넣기. #1 GraphQL서버 외부 연동 서버 DB POST /graphql
  • 12. GraphQL 끼워넣기 #2 GraphQL서버 인증서버 상품서버 외부서버 기존 Rest API 내부서버 POST /graphql DB 지양(/graphql 단일 endpoint 지향) bypass
  • 13. 회사와 사람 코드로 두 node(Entity)로 관계를 지어보자. 샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
  • 14. 회사와 사람 const UserType = new GraphQLObjectType({ name: 'User', // GraphQL Object Name(필수) fields: () => ({ id: {type: GraphQLString}, firstName: {type: GraphQLString}, age: {type: GraphQLInt}, companyId: {type: GraphQLString}, company: { type: CompanyType, resolve(parentValue, args) { console.log(parentValue, args); return axios.get(`${SERVER_DOMAIN}/companies/${parentValue.companyId}`) .then(req => req.data); } } }) }); #사람이 먼저다. 연결(user -> company)
  • 15. 회사와 사람 const CompanyType = new GraphQLObjectType({ name: 'Company', fields: () => ({ id: {type: GraphQLString}, name: {type: GraphQLString}, description: {type: GraphQLString}, users: { type: new GraphQLList(UserType), resolve(parentValue, args) { return axios.get(`${SERVER_DOMAIN}/companies/${parentValue.id}/users`) .then(req => req.data); } } }) }); 연결(company -> users)
  • 16. RootQuery Query(조회) 시 시작될 수 있는 node 를 지정하여야 한다. 따라서 Entity product는 RootQuery에 없으므로 user, company의 field로만 접근 할 수 있다.
  • 17. RootQuery 지정 const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: () => ( { user: { type: UserType, args: {id: {type: GraphQLString}}, resolve(parentValue, args) { return axios.get(`${SERVER_DOMAIN}/users/${args.id}`) .then(req => req.data); } }, company: { type: CompanyType, args: {id: {type: GraphQLString}}, resolve(parentValue, args) { return axios.get(`${SERVER_DOMAIN}/companies/${args.id}`) .then(req => req.data); } } }) });
  • 18. 이제 호출해보자. GraphiQL 작성한 Schema를 보고 Query를 작성하고 유효성을 검사하면서 테스트를 할 수 있는 good dev tool 설치버전도 있고, 서버 띄울때 함께 띄울수 있다. 샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
  • 19. { user(id: "23") { id firstName company { name } } } { "data": { "user": { "id": "23", "firstName": "ko", "company": { "name": "tomorrow" } } } } User정보와 회사정보를 가져오는 샘플
  • 20. { company(id: "1") { id name description users { id firstName age } } } { "data": { "company": { "id": "1", "name": "tomorrow", "description": "111st", "users": [ { "id": "23", "firstName": "ko", "age": 20 }, { "id": "40", "firstName": "lee", "age": 40 }, { "id": "44", "firstName": "ra", "age": 45 } ] } } } Company정보와 users를 가져오는 샘플
  • 21. Mutation 변경작업(추가, 수정, 삭제) Response Type에 따라서 Query를 원하는대로 데이타를 받을 수도 있다.
  • 22. Mutation - User 추가 const mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addUser: { type: UserType, args: { firstName: {type: new GraphQLNonNull(GraphQLString)}, age: {type: new GraphQLNonNull(GraphQLInt)}, companyId: {type: GraphQLString} }, resolve(parentValue, {firstName, age}) { return axios.post(`${SERVER_DOMAIN}/users`, {firstName, age}) .then(res => res.data); } }, deleteUser: {…}, editUser: {…} } })
  • 23. mutation { addUser( firstName: “gu", age: 40 ) { id firstName age } } { "data": { "addUser": { "id": "SJ0Wox-i-", "firstName": "gu", "age": 40 } } } mutation을 이용한 유저 추가 및 생성 정보 받기
  • 24. Mutation - User 삭제 const mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addUser: {…}, deleteUser: { type: UserType, args: { id: {type: new GraphQLNonNull(GraphQLString)} }, resolve(parentValue, {id}) { return axios.delete(`${SERVER_DOMAIN}/users/${id}`) .then(res => res.data); } }, editUser: {…} } })
  • 25. mutation { deleteUser( id : "SJ0Wox-i-" ) { id } } { "data": { "deleteUser": { "id": null } } } mutation을 이용한 유저 삭제
  • 26. Mutation - User 수정 const mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addUser: {…}, deleteUser: {…}, editUser: { type: UserType, args: { id: {type: new GraphQLNonNull(GraphQLString)}, firstName: {type: GraphQLString}, age: {type: GraphQLInt}, companyId: {type: GraphQLString} }, resolve(parentValue, args) { return axios.patch(`${SERVER_DOMAIN}/users/${args.id}`, args) .then(res => res.data); } } } })
  • 27. mutation { editUser( id: "44", firstName: "ra", age: 45 ) { id firstName age company { id name, description } } } { "data": { "editUser": { "id": "44", "firstName": "ra", "age": 45, "company": { "id": "1", "name": "tomorrow", "description": "111st" } } } } mutation을 이용한 유저 수정(Patch)
  • 28. FrontEnd Client 3총사 • Apollo client(http://dev.apollodata.com/) - All in one • relay(https://facebook.github.io/relay/) - performance • Lokka(https://github.com/kadirahq/lokka) - Simple
  • 29. URL • slide 예제소스.(https://github.com/gidong-lee/graphQL_exam) - 예제쿼리, 소스, 동작방법등 기술. • GraphiQL(https://github.com/graphql/graphiql) • udemy 강의 추천(https://www.udemy.com/graphql-with-react-course) - 영어가 힘드시면 저처럼 크롬으로 강의 한글번역해서 보시면 보기 편합 니다. - 크롬으로 강의시작 -> 자막 on(영문) -> 한글로 번역 -> 나쁘지않게 번역 됨. • graphql query check eslint (https://github.com/apollographql/eslint-plugin-graphql)
  • 30. FIN