Skip to content

Instantly share code, notes, and snippets.

@komkanit
Created February 14, 2018 03:43
Show Gist options
  • Save komkanit/f21857ff5566919019f7858d2e37a762 to your computer and use it in GitHub Desktop.
Save komkanit/f21857ff5566919019f7858d2e37a762 to your computer and use it in GitHub Desktop.
import ApolloClient from 'apollo-client';
import { getOperationAST } from 'graphql';
import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'isomorphic-fetch';
import WebSocket from 'ws';
let apolloClient = null;
if (!process.browser) {
global.fetch = fetch;
}
const initNetworkInterface = (headers) => {
const httpLink = new HttpLink({
uri: `${process.env.API_HOST}/graphql`,
headers,
credentials: 'include',
});
const wsLink = new WebSocketLink({
uri: `${process.env.SOCKET_API}/subscriptions`,
options: {
reconnect: true,
},
webSocketImpl: !process.browser && WebSocket,
});
const link = ApolloLink.split(
(operation) => {
const operationAST = getOperationAST(operation.query, operation.operationName);
return !!operationAST && operationAST.operation === 'subscription';
},
wsLink,
httpLink,
);
return link;
};
const createClient = (initialState, headers) =>
new ApolloClient({
ssrMode: !process.browser,
ssrForceFetchDelay: 100,
link: initNetworkInterface(headers),
cache: new InMemoryCache().restore(initialState),
});
export default (initialState, headers) => {
if (!process.browser) {
return createClient(initialState, headers);
}
if (!apolloClient) {
apolloClient = createClient(initialState, headers);
}
return apolloClient;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment