import gql from 'graphql-tag'; import { ApolloClient } from 'apollo-client'; import { createHttpLink } from 'apollo-link-http'; import { setContext } from 'apollo-link-context'; import { InMemoryCache } from 'apollo-cache-inmemory'; import Octokit from '@octokit/rest'; import resetURL from './resetURL'; import { setCookie, getCookie } from './cookie'; const getGithubClient = () => { // token const c = /\?code=([^?]+)/; const code = (c.exec(window.location.search) || [])[1]; resetURL(); return new Promise((resolve, reject) => code ? resolve(code) : reject('not logged in') ) .then(code => { const token = getCookie('token'); if (token) return token; console.log('first login'); const proxy = new ApolloClient({ link: createHttpLink({ uri: 'https://like-water.netlify.com/.netlify/functions/graphql' }), cache: new InMemoryCache() }); return proxy .query({ query: gql` query { token(code: "${code}") { access_token } } ` }) .then(({ data: { token: { access_token } } }) => { setCookie('token', access_token); return access_token; }); }) .then(token => { // basic auth return new Octokit({ auth: token }); }); }; export default getGithubClient;