使用Apollo-Client对GitHub API v4进行身份验证

时间:2017-12-27 13:04:43

标签: javascript reactjs github-api apollo apollo-client

GitHub的新GraphQL API需要使用令牌进行身份验证,因为之前的版本。那么,我们如何在Apollo-Client内的HttpLink中添加“标题”信息?

const client = new ApolloClient({
  link: new HttpLink({ uri: 'https://api.github.com/graphql' }),
  cache: new InMemoryCache()
});

1 个答案:

答案 0 :(得分:5)

您可以使用apollo-link-context定义授权标头,然后选中the header section

为Github API使用apollo-client的完整示例如下:

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';

const token = "YOUR_ACCESS_TOKEN";

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql' })),
  cache: new InMemoryCache()
});

client.query({
  query: gql`
    query ViewerQuery {
      viewer {
        login
     }
    }
  `
})
  .then(resp => console.log(resp.data.viewer.login))
  .catch(error => console.error(error));