シュッとーく #01 (永和社内イベント)
(株)永和システムマネジメント@mtsmfm松島 史秋シュッと学ぶGraphQL/Relay
View Slide
※ 仕事ではまだ使えてないのであんまりつっこまれてもこまるよ
GraphQL とは
http://graphql.org/
API のためのクエリ言語
REST API の問題
User 1-* Tweet
/users[{id: 1},{id: 2}]
/users/1/tweets[{id: 1, body: ‘hi’},{id: 2, body: ‘bye’}]
/users/2/tweets[{id: 3, body: ‘あ’},{id: 4, body: ‘い’}]
/users/users/1/tweets/users/2/tweets...
クライアント N+1
/users[{id: 1tweets: [{id: 1, body: ‘hi’},{id: 2, body: ‘bye’},]},{id: 2...
- ふぁぼも欲しい- プロフィールも- ツイートのRTも
そこでクエリ言語
/graphqlquery {users {idtweets {id, body}}}
何が欲しいかを書く
エンドポイントは1つ
- query- mutation
- query (GET)- mutation (POST)みたいなもの
POST /tweets{tweet: {body: ‘hi’}}# => {id: 1, body: ‘hi’}
/graphqlmutation {createTweet(body: ‘hi’) {tweetEdge {id, body}}}
Relay
React のコンポーネントをGraphQL に紐付ける
コンポーネントは何が欲しいかを宣言する
class Tweet extends React.Component {render () {return ({this.props.tweet.body})}}
class Tweet extends React.Component {render () {return ({this.props.tweet.body})}}Relay.createContainer(Tweet, {fragments: {tweet: () => Relay.QL`fragment on Tweet {body}`}}
子の分は親が面倒を見る
class App extends React.Component {render () {return ()}}Relay.createContainer(App, {fragments: {tweet: () => Relay.QL`fragment on Tweet {${Tweet.getFragment(‘tweet’)}`}}
GraphQL はあくまでクエリ言語
Relay がうまいこと動くためにGraphQL 上で実装しないといけない仕様
http://facebook.github.io/relay/docs/getting-started.html#content
Object Identification
Relay は Store 込みキャッシュとかもいい感じ(詳細はよく知らない)に扱う
特定のオブジェクト“だけ”の更新が必要になる場合がある
query {node(id: ‘RmFjdGlvbjox’)id, body}}
query {node(id: ‘RmFjdGlvbjox’)id, body}}オブジェクトのグローバル ID
Connection
query {users {tweets(first: 5,after: ‘RmFjdGlvbjox’) {edges {node {id, body}pageInfo {hasNextPage}}}}
Cursor basedPagination無限スクロール
Offset basedPagination<- < 1, [2], 3 > ->
(特に流速が速いと)offset でやると見落としてしまう
我々の頭はあまりにoffset ベースに慣れすぎている
(流速が遅いと)「あの辺」という脳内インデックスができる
この辺https://dev-blog.apollodata.com/understanding-pagination-rest-graphql-and-relay-b10f835549e7#.n34gvtqr5
まとめ
GraphQL/Relay によって- クライアント N+1 が解消する- クライアント(コンポーネント)が必要なものを自分で宣言して取ってこれる- リクエストを投げて Store に放り込んでコンポーネントに繋げるまでを考える戦いに終止符が打たれる- Schema による秩序が靠らされる
とりあえず GitHub のGraphQL であそんでみてはhttps://developer.github.com/early-access/graphql/explorer/https://github.com/github/github-graphql-rails-example/
その後は素振りhttps://github.com/gauravtiwari/relay-rails-blog/https://github.com/rmosolgo/graphql-ruby
よく知らない/素振れてないこと- Validation- Auth- 親の variable が必要な Mutation
CreditsBackground pattern from subtlepatterns.comEmoji provided free by Emoji One