Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Created June 21, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luandevpro/8bc0f8f2041ed7c804d13f40393bdcbb to your computer and use it in GitHub Desktop.
Save luandevpro/8bc0f8f2041ed7c804d13f40393bdcbb to your computer and use it in GitHub Desktop.
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
const scheme = proto => (window.location.protocol === 'https:' ? `${proto}s` : proto);
const HASURA_GRAPHQL_ENGINE_HOSTNAME = 'cjs-chat.herokuapp.com';
export const GRAPHQL_ENDPOINT = `${scheme('https')}://${HASURA_GRAPHQL_ENGINE_HOSTNAME}/v1/graphql`;
export const WEBSOCKET_ENDPOINT = `${scheme('wss')}://${HASURA_GRAPHQL_ENGINE_HOSTNAME}/v1/graphql`;
function initialApollo(ACCESS_TOKEN) {
const httpLink = new HttpLink({
uri: GRAPHQL_ENDPOINT,
headers: {
Authorization: `Bearer ${ACCESS_TOKEN}`,
},
});
const wsLink = new WebSocketLink({
uri: WEBSOCKET_ENDPOINT,
options: {
lazy: true,
reconnect: true,
headers: {
Authorization: `Bearer ${ACCESS_TOKEN}`,
},
},
});
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink
);
return new ApolloClient({
link,
cache: new InMemoryCache({
addTypename: false,
}),
});
}
export default initialApollo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment