SlideShare a Scribd company logo
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에 대한 정보를 볼수 있고 Query도 실행/검증 가능
-> 매개변수에 대한 검증도 FE의 요청쿼리에 대한 validation 가능하다. eslint-plugin-graphq
-> GraphQL이 알아서 해준다.
-> GraphQL을 쓰면 신경 안써도 된다. 스키마만 업데이트 해주면 된다.
블로그 : https://githubengineering.com/the-github-graphql-api/
­ Github 개발팀.
“그래서 GraphQL”
이제 조금씩 알아보자.
Rest API vs GraphQL
HTTP상의 Endpoint 비교
▪ 리스트 조회 : GET /api/posts
▪ 조회 : GET /api/posts/1
▪ 생성 : POST /api/posts
▪ 치환(수정) : PUT or PATCH /api/posts/1
▪ 삭제 : DELETE /api/posts/1
Rest API
▪ POST /graphql
- 리스트, 조회, 생성, 수정, 삭제등
GraphQL
엔티티별
전체
간단하게 Database의 console에 붙어서 Query한다 생각하면 편하다.
다만 Query의 스펙을 미리 정의(=Schema) 해놓아야만 한다.
에 따라서 

입력을
조회를 

수정을 

삭제를
있다.
GraphQL Server가
할일
Node 정의
•개별 node를 정의.

예 : 유저, 글, 댓글, 회사, 상품,

판매자
Node 간 관계설정
•node에 관계 필드를 추가.

- user node에 companyInfo
추가

- company node에 users 추가
•관계 필드에 대해서 Store 연결.

- companyInfo필드의 Type은 

CompanyType

- users 필드의 Type은 

GraphQLList(UserType)과 같이 

감싸준다.
노드(점)의 관계 필드(선)가 곧 Store 연결(=DB 조회)
Root Query 생성.
userList
noticeList
productList
user
noticeById
Root Query
Root Query?
•REST API의 여러 조회용 END POINT의 모음이라 생각하면 이해하기 쉽다.
즉. Entry Point를 제공자가 정의해주는 것이다.
• RootQuery는 의미적인 표현인 것이고 일반 node와 Type/동작 동일.

= GraphQLObjectType
•다만 의미적으로 Root Query Node의 경우에는 다른 node를 참조만 하고,

다른 노드로 부터 참조되지 않는다.
GraphQL로 서비스 구성 예
GraphQL서버
외부 연동 서버
DB
POST /graphql
DB든 외부연동서버든 처리할 데이타에 대해서는 Node 정의를 해주어야 합니다.
GraphQL로 서비스 #2
GraphQL서버
인증서버
상품서버
외부서버
기존 Rest API
내부서버
POST /graphql
DB
지양(/graphql 단일 endpoint 지향)
bypass
여기서도 GraphQL서버에서 Composite을 위해서 서버별 타입별로 Node정의를 해주어야 한다.
만약 A,B 서버에 동일하게 생긴 Node가 있더라도 관계설정이 달라질수 있으므로

각각을 구분해주어야 한다.
GraphQL Query 사용시 주요
장점.
•FE/Native의 요청 필드만 리턴하므로 Overfetch 방지.
•MSA 구조에서 여러 서버의 데이타를 효율적으로 Data
Integration 한다.
•REST API에서 2~3회 요청에 걸쳐 데이타를 가져오는 경우를 

간단하게 1 회 요청으로 끝낼 수 있다.(유연성 甲)

# BE 개발자가 별도 Endpoint 추가하고 로직으로 풀던 문제
를 쉽게 끝낼 수 있다.
전체 구조
이렇게도 나누는것도 가능은 할듯.
코드를 보면 이렇게도 가능할 것으로 생각된다.

다만 아래와 같이 나눌 경우 동일 데이타에 대해서 변경과 조회가
함께 일어나므로 시점에 따라 값이 달라질수도 있는 문제가 발생 할 수 있다.
회사와 사람 Node

코드로 두 Node로 관계를 지어보자.
샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
샘플코드에 대해서.
•axios는 back 단 rest api를 호출해주는

jQuery의 ajax같은 라이브러리다.

(예 : 자바의 RestTemplate)
•JSON Server라는 json파일을 읽어 쉽게 개발/목킹용 rest
api 

서버를 만들어 주는 녀석이다.

입력,수정,삭제,페이징등을 모두 처리해준다.

GitHub : https://github.com/typicode/json-server
User Type
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)
위의 fields.company 필드가 관계필드가 된다.
관계 필드는 곧 DB/Cache/rest server 연결(=DB 조회)을 뜻한다.
코드의 axios는 뒤단의 rest api를 호출하여 데이타를 가져오는 것이니 크게신경 안써도 됨.
Company Type
const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: () => ({
id: {type: GraphQLString},
name: {type: GraphQLString},
description: {type: GraphQLString},
users: {
type: new GraphQLList(UserType),
args: {limit: {type: GraphQLInt}},
resolve(parentValue, args) {

const { limit = 20 } = args;
return axios.get(

`${SERVER_DOMAIN}/companies/${parentValue.id}/users?_limit=${limit}`

).then(req => req.data);
}
}
})
});
연결(company -> users)
위의 fields.users 필드가 관계필드가 된다.
관계 필드는 곧 DB/Cache/rest server 연결(=DB 조회)을 뜻한다.
users필드의 타입이 GraphQLList(UserType)인 것을 잘 숙지하자.
Root Query
Query(조회) 시 시작될 수 있는 node 를 지정하여야 한다.

따라서 node product 조회는 RootQuery 필드에 없으므로 company를 통해서만 접근 할 수 있다.
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);
}
}
})
});
관계 필드의 resolve 함수?
const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: () => ({
id: {type: GraphQLString},
name: {type: GraphQLString},
description: {type: GraphQLString},
users: {
type: new GraphQLList(UserType),
args: {limit: {type: GraphQLInt}},
resolve(parentValue, args) {
const { limit = 20 } = args;
return axios.get(

`${SERVER_DOMAIN}/companies/${parentValue.id}/users?_limit=${limit}`

).then(req => req.data);
}
}
})
});
args -> Query 호출시에 적어주는 값. 

예 : id, searchKeyword, limit, first, last, page, lastNum
parentValue -> 나의 상위에서 주입해준 값.

user의 Company에서 조회하여 리턴해준값
이제 호출해보자.
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 사용시 장점.
•사실 로직적으로 내부적으로 변경하는 로직을 있는것 뿐 조회
Query와 구조적으로는 같다.
•Mutation query를 호출하더라도 해당 Mutation의 Return
Type에 따라서 Response를 자유롭게 변경 할 수 있다.
Mutation - User 추가
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addUser: {
type: UserType,
args: {
firstName: {type: new GraphQLNonNull(GraphQLString)},
age: {type: new GraphQLNonNull(GraphQLInt)} },
resolve(parentValue, {firstName, age}) {
return axios.post(`${SERVER_DOMAIN}/users`, {firstName, age})
.then(res => res.data);
}
},
deleteUser: {…},
editUser: {…}
}
})
코드의 axios는 뒤단의 rest api를 POST로 호출하여 데이타를 저장하는 부분이다.
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);
}
}
}
})
GraphQL을 안쓸때 상황.
•login.json에 userName이랑 image좀 추가해주세요.
•NoticeList.json에서는 id, title, 작성자만 필요하니 나머지는
빼주세요.
•몇일있다가 수정일은 추가해주세요.
•이 데이타는 결과에 따라서 추가 Request가 필요하므로 서버
에서 한번에 말아주세요.
•하위 호환 때문에 API 버전 변경이 필요해요.
GraphQL을 쓰게되면.
•Root Query에 머하나 추가해주세요.
•A 랑 B랑 릴레이션 맺어주심 안돼요?
•mutation 추가해주세요.
•커피 한 잔 하러 가시죠.
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

- 다양한 플랫폼 지원(FE(vanilla/react/angular), Native)
•relay(https://facebook.github.io/relay/) 

- FE단 캐싱을 통해 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

More Related Content

PPTX
GraphQL overview
PPTX
Nodejs, PhantomJS, casperJs, YSlow, expressjs
PDF
ReactJS | 서버와 클라이어트에서 동시에 사용하는
PDF
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
PDF
ReactJS로 시작하는 멀티플랫폼 개발하기
PPTX
ECMAScript 6의 새로운 것들!
PPTX
[115] clean fe development_윤지수
PDF
GKAC 2014 Nov. - 안드로이드 스튜디오로 생산성 올리기
GraphQL overview
Nodejs, PhantomJS, casperJs, YSlow, expressjs
ReactJS | 서버와 클라이어트에서 동시에 사용하는
GraphQL in Action - REST와 이별할 때 생각해야 하는 것들
ReactJS로 시작하는 멀티플랫폼 개발하기
ECMAScript 6의 새로운 것들!
[115] clean fe development_윤지수
GKAC 2014 Nov. - 안드로이드 스튜디오로 생산성 올리기

What's hot (20)

PDF
Express 프레임워크
PDF
[213]monitoringwithscouter 이건희
PPT
헷갈리는 자바스크립트 정리
PDF
React 튜토리얼 1차시
PDF
React 튜토리얼 2차시
PDF
React Native를 사용한
 초간단 커뮤니티 앱 제작
PPTX
Angular2 router&http
PDF
진짜기초 Node.js
PDF
비전공자의 자바스크립트 도전기
PPTX
안드로이드 개발자에 필요한 오픈소스이야기
PDF
Mean 스택을 사용한 IoT 개발
PPTX
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
PDF
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
PPTX
[하코사 세미나] 비전공자의 자바스크립트 도전기
PPTX
반복적인 작업이 싫은 안드로이드 개발자에게
PDF
03.실행환경 교육교재(배치처리)
PPTX
Startup JavaScript 8 - NPM, Express.JS
PDF
Parse.com 맛보기
PPTX
REST API 설계
PDF
Resource Handling in Spring MVC
Express 프레임워크
[213]monitoringwithscouter 이건희
헷갈리는 자바스크립트 정리
React 튜토리얼 1차시
React 튜토리얼 2차시
React Native를 사용한
 초간단 커뮤니티 앱 제작
Angular2 router&http
진짜기초 Node.js
비전공자의 자바스크립트 도전기
안드로이드 개발자에 필요한 오픈소스이야기
Mean 스택을 사용한 IoT 개발
[하코사세미나]미리보는 대규모 자바스크립트 어플리케이션 개발
제 5회 Lisp 세미나 - 클로저 개발팀을 위한 지속적인 통합
[하코사 세미나] 비전공자의 자바스크립트 도전기
반복적인 작업이 싫은 안드로이드 개발자에게
03.실행환경 교육교재(배치처리)
Startup JavaScript 8 - NPM, Express.JS
Parse.com 맛보기
REST API 설계
Resource Handling in Spring MVC
Ad

Similar to GraphQL overview #2 (20)

PDF
overview of spring4
PPTX
[112]rest에서 graph ql과 relay로 갈아타기 이정우
PPTX
Ksug 세미나 (윤성준) (20121208)
PDF
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
PDF
Isomorphicspring Isomorphic - spring web seminar 2015
PDF
Hello, GraphQL!
PPTX
Golang Project Guide from A to Z: From Feature Development to Enterprise Appl...
PPTX
Booting Spring Data REST
PDF
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
PPTX
About Visual C++ 10
PDF
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
PPTX
자바스크립트 클래스의 프로토타입(prototype of class)
PDF
파이썬 데이터베이스 연결 2탄
PPTX
Domain Specific Languages With Groovy
PPTX
[114]angularvs react 김훈민손찬욱
PPT
Ai C#세미나
PDF
7가지 동시성 모델 람다아키텍처
PPTX
Mongo db 최범균
PDF
Ryu with OpenFlow 1.3, REST API
PDF
함수적 사고 2장
overview of spring4
[112]rest에서 graph ql과 relay로 갈아타기 이정우
Ksug 세미나 (윤성준) (20121208)
GKAC 2015 Apr. - Battery, 안드로이드를 위한 쉬운 웹 API 호출
Isomorphicspring Isomorphic - spring web seminar 2015
Hello, GraphQL!
Golang Project Guide from A to Z: From Feature Development to Enterprise Appl...
Booting Spring Data REST
[제3회 스포카콘] React + TypeScript + GraphQL 으로 시작하는 Web Front-End
About Visual C++ 10
[IT기술칼럼#2] 고급자바스크립트 for AngularJS, React_고급자바스크립트,AngularJS,React전문교육학원
자바스크립트 클래스의 프로토타입(prototype of class)
파이썬 데이터베이스 연결 2탄
Domain Specific Languages With Groovy
[114]angularvs react 김훈민손찬욱
Ai C#세미나
7가지 동시성 모델 람다아키텍처
Mongo db 최범균
Ryu with OpenFlow 1.3, REST API
함수적 사고 2장
Ad

GraphQL overview #2

  • 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에 대한 정보를 볼수 있고 Query도 실행/검증 가능 -> 매개변수에 대한 검증도 FE의 요청쿼리에 대한 validation 가능하다. eslint-plugin-graphq -> GraphQL이 알아서 해준다. -> GraphQL을 쓰면 신경 안써도 된다. 스키마만 업데이트 해주면 된다. 블로그 : https://githubengineering.com/the-github-graphql-api/
  • 7. Rest API vs GraphQL HTTP상의 Endpoint 비교 ▪ 리스트 조회 : GET /api/posts ▪ 조회 : GET /api/posts/1 ▪ 생성 : POST /api/posts ▪ 치환(수정) : PUT or PATCH /api/posts/1 ▪ 삭제 : DELETE /api/posts/1 Rest API ▪ POST /graphql - 리스트, 조회, 생성, 수정, 삭제등 GraphQL 엔티티별 전체
  • 8. 간단하게 Database의 console에 붙어서 Query한다 생각하면 편하다. 다만 Query의 스펙을 미리 정의(=Schema) 해놓아야만 한다. 에 따라서 
 입력을 조회를 
 수정을 
 삭제를 있다.
  • 10. Node 정의 •개별 node를 정의.
 예 : 유저, 글, 댓글, 회사, 상품,
 판매자
  • 11. Node 간 관계설정 •node에 관계 필드를 추가.
 - user node에 companyInfo 추가
 - company node에 users 추가 •관계 필드에 대해서 Store 연결.
 - companyInfo필드의 Type은 
 CompanyType
 - users 필드의 Type은 
 GraphQLList(UserType)과 같이 
 감싸준다. 노드(점)의 관계 필드(선)가 곧 Store 연결(=DB 조회)
  • 13. Root Query? •REST API의 여러 조회용 END POINT의 모음이라 생각하면 이해하기 쉽다. 즉. Entry Point를 제공자가 정의해주는 것이다. • RootQuery는 의미적인 표현인 것이고 일반 node와 Type/동작 동일.
 = GraphQLObjectType •다만 의미적으로 Root Query Node의 경우에는 다른 node를 참조만 하고,
 다른 노드로 부터 참조되지 않는다.
  • 14. GraphQL로 서비스 구성 예 GraphQL서버 외부 연동 서버 DB POST /graphql DB든 외부연동서버든 처리할 데이타에 대해서는 Node 정의를 해주어야 합니다.
  • 15. GraphQL로 서비스 #2 GraphQL서버 인증서버 상품서버 외부서버 기존 Rest API 내부서버 POST /graphql DB 지양(/graphql 단일 endpoint 지향) bypass 여기서도 GraphQL서버에서 Composite을 위해서 서버별 타입별로 Node정의를 해주어야 한다. 만약 A,B 서버에 동일하게 생긴 Node가 있더라도 관계설정이 달라질수 있으므로
 각각을 구분해주어야 한다.
  • 16. GraphQL Query 사용시 주요 장점. •FE/Native의 요청 필드만 리턴하므로 Overfetch 방지. •MSA 구조에서 여러 서버의 데이타를 효율적으로 Data Integration 한다. •REST API에서 2~3회 요청에 걸쳐 데이타를 가져오는 경우를 
 간단하게 1 회 요청으로 끝낼 수 있다.(유연성 甲)
 # BE 개발자가 별도 Endpoint 추가하고 로직으로 풀던 문제 를 쉽게 끝낼 수 있다.
  • 18. 이렇게도 나누는것도 가능은 할듯. 코드를 보면 이렇게도 가능할 것으로 생각된다.
 다만 아래와 같이 나눌 경우 동일 데이타에 대해서 변경과 조회가 함께 일어나므로 시점에 따라 값이 달라질수도 있는 문제가 발생 할 수 있다.
  • 19. 회사와 사람 Node
 코드로 두 Node로 관계를 지어보자. 샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
  • 20. 샘플코드에 대해서. •axios는 back 단 rest api를 호출해주는
 jQuery의 ajax같은 라이브러리다.
 (예 : 자바의 RestTemplate) •JSON Server라는 json파일을 읽어 쉽게 개발/목킹용 rest api 
 서버를 만들어 주는 녀석이다.
 입력,수정,삭제,페이징등을 모두 처리해준다.
 GitHub : https://github.com/typicode/json-server
  • 21. User Type 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) 위의 fields.company 필드가 관계필드가 된다. 관계 필드는 곧 DB/Cache/rest server 연결(=DB 조회)을 뜻한다. 코드의 axios는 뒤단의 rest api를 호출하여 데이타를 가져오는 것이니 크게신경 안써도 됨.
  • 22. Company Type const CompanyType = new GraphQLObjectType({ name: 'Company', fields: () => ({ id: {type: GraphQLString}, name: {type: GraphQLString}, description: {type: GraphQLString}, users: { type: new GraphQLList(UserType), args: {limit: {type: GraphQLInt}}, resolve(parentValue, args) {
 const { limit = 20 } = args; return axios.get(
 `${SERVER_DOMAIN}/companies/${parentValue.id}/users?_limit=${limit}`
 ).then(req => req.data); } } }) }); 연결(company -> users) 위의 fields.users 필드가 관계필드가 된다. 관계 필드는 곧 DB/Cache/rest server 연결(=DB 조회)을 뜻한다. users필드의 타입이 GraphQLList(UserType)인 것을 잘 숙지하자.
  • 23. Root Query Query(조회) 시 시작될 수 있는 node 를 지정하여야 한다.
 따라서 node product 조회는 RootQuery 필드에 없으므로 company를 통해서만 접근 할 수 있다.
  • 24. 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); } } }) });
  • 25. 관계 필드의 resolve 함수? const CompanyType = new GraphQLObjectType({ name: 'Company', fields: () => ({ id: {type: GraphQLString}, name: {type: GraphQLString}, description: {type: GraphQLString}, users: { type: new GraphQLList(UserType), args: {limit: {type: GraphQLInt}}, resolve(parentValue, args) { const { limit = 20 } = args; return axios.get(
 `${SERVER_DOMAIN}/companies/${parentValue.id}/users?_limit=${limit}`
 ).then(req => req.data); } } }) }); args -> Query 호출시에 적어주는 값. 
 예 : id, searchKeyword, limit, first, last, page, lastNum parentValue -> 나의 상위에서 주입해준 값.
 user의 Company에서 조회하여 리턴해준값
  • 26. 이제 호출해보자. GraphiQL 작성한 Schema를 보고 Query를 작성하고 유효성을 검사하면서 테스트를 할 수 있는 good dev tool 설치버전도 있고, 서버 띄울때 함께 띄울수 있다. 샘플을 실행시켜보려면 https://github.com/gidong-lee/graphQL_exam
  • 27. { user(id: "23") { id firstName company { name } } } { "data": { "user": { "id": "23", "firstName": "ko", "company": { "name": "tomorrow" } } } } User정보와 회사정보를 가져오는 샘플
  • 28. { 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를 가져오는 샘플
  • 29. Mutation 변경작업(추가, 수정, 삭제) Response Type에 따라서 Query를 원하는대로 데이타를 받을 수도 있다.
  • 30. Mutation 사용시 장점. •사실 로직적으로 내부적으로 변경하는 로직을 있는것 뿐 조회 Query와 구조적으로는 같다. •Mutation query를 호출하더라도 해당 Mutation의 Return Type에 따라서 Response를 자유롭게 변경 할 수 있다.
  • 31. Mutation - User 추가 const mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addUser: { type: UserType, args: { firstName: {type: new GraphQLNonNull(GraphQLString)}, age: {type: new GraphQLNonNull(GraphQLInt)} }, resolve(parentValue, {firstName, age}) { return axios.post(`${SERVER_DOMAIN}/users`, {firstName, age}) .then(res => res.data); } }, deleteUser: {…}, editUser: {…} } }) 코드의 axios는 뒤단의 rest api를 POST로 호출하여 데이타를 저장하는 부분이다.
  • 32. mutation { addUser(
 firstName: “gu", age: 40 ) { id firstName age } } { "data": { "addUser": { "id": "SJ0Wox-i-", "firstName": "gu", "age": 40 } } } mutation을 이용한 유저 추가 및 생성 정보 받기
  • 33. 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: {…} } })
  • 34. mutation { deleteUser(
 id : "SJ0Wox-i-"
 ) { id } } { "data": { "deleteUser": { "id": null } } } mutation을 이용한 유저 삭제
  • 35. 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); } } } })
  • 36. GraphQL을 안쓸때 상황. •login.json에 userName이랑 image좀 추가해주세요. •NoticeList.json에서는 id, title, 작성자만 필요하니 나머지는 빼주세요. •몇일있다가 수정일은 추가해주세요. •이 데이타는 결과에 따라서 추가 Request가 필요하므로 서버 에서 한번에 말아주세요. •하위 호환 때문에 API 버전 변경이 필요해요.
  • 37. GraphQL을 쓰게되면. •Root Query에 머하나 추가해주세요. •A 랑 B랑 릴레이션 맺어주심 안돼요? •mutation 추가해주세요. •커피 한 잔 하러 가시죠.
  • 38. 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)
  • 39. FrontEnd Client 3총사 •Apollo client(http://dev.apollodata.com/)
 - All in one
 - 다양한 플랫폼 지원(FE(vanilla/react/angular), Native) •relay(https://facebook.github.io/relay/) 
 - FE단 캐싱을 통해 Performance가 좋음.
 - 러닝커브가 있다. •Lokka(https://github.com/kadirahq/lokka)
 - Simple
  • 40. 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)
  • 41. FIN