GitHub API v4のGraphQLをaxiosとApolloで叩いてみる
ググっても最小限のサンプルがなかったので調べて試した。node環境を想定。
axiosで叩いてみる
npm i axios
しておく。
const axios = require('axios') const accessToken = 'xxxxxxxxxxxxxxxxxxxxxx' axios({ url: 'https://api.github.com/graphql', headers: { Authorization: `bearer ${accessToken}`, Accept: 'application/vnd.github.v4.idl' }, method: 'POST', data: { query: `query { repository(owner: "vuejs", name: "vue") { name, description, license } }` } }) .then(res => res.data) .then(console.log)
実行すると👇のが返ってくる
{ data: { repository: { name: 'vue', description: 'A progressive, incrementally-adoptable JavaScript framework for building UI on the web.', license: 'MIT License' } } }
accessToken
accesToken
はAPIの認証用のトークン。こことかcurlで取得しておく。
漏れるとダメなやつなのでpublishするときは環境変数とかに入れときましょう。
Apolloで叩く
package.json
パッケージがいろいろ必要。npm i
しておく。
{ "dependencies": { "apollo-cache-inmemory": "^1.1.4", "apollo-client": "^2.0.4", "apollo-link": "^1.0.7", "apollo-link-http": "^1.3.2", "graphql": "^0.12.3", "graphql-tag": "^2.6.1", "node-fetch": "^1.7.3" } }
コード
const gql = require('graphql-tag') const access_token = 'xxxxxxxxxxxxxxxxxxxx' const {ApolloClient } = require('apollo-client') const {HttpLink } = require('apollo-link-http') const {ApolloLink, concat} = require('apollo-link') const {InMemoryCache } = require('apollo-cache-inmemory') const fetch = require('node-fetch') const authMiddleware = new ApolloLink((operation, forward) => { operation.setContext({ headers: { Authorization: `bearer ${access_token}`, Accept: 'application/vnd.github.v4.idl', } }) return forward(operation) }) const httpLink = new HttpLink({ uri: 'https://api.github.com/graphql' , fetch}) const client = new ApolloClient({ link: concat(authMiddleware, httpLink), cache: new InMemoryCache() }) client.query({ query: gql`{ repository(owner: "vuejs", name: "vue") { name, description }}` }).then(console.log)
headerの設定が若干めんどくさい。
実行すると👇のが返ってくる。
{ data: { repository: { name: 'vue', description: 'A progressive, incrementally-adoptable JavaScript framework for building UI on the web.', __typename: 'Repository' } }, loading: false, networkStatus: 7, stale: false }
graphql-tag
graphql-tag
がGraphQLのquery書くのに便利なやつぽい雰囲気。