Skip to content

Instantly share code, notes, and snippets.

@catalinpit
Created March 14, 2022 13:12
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 catalinpit/839c22b0a430c5b690a3d2d409115674 to your computer and use it in GitHub Desktop.
Save catalinpit/839c22b0a430c5b690a3d2d409115674 to your computer and use it in GitHub Desktop.
import { ApolloClient, HttpLink, InMemoryCache, split } from "@apollo/client";
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from "graphql-ws";
import { getMainDefinition } from "@apollo/client/utilities";
const GRAPHQL_ENDPOINT = "realtime-poll.hasura.app";
const scheme = (proto) =>
window.location.protocol === "https:" ? `${proto}s` : proto;
const wsURI = `${scheme("ws")}://${GRAPHQL_ENDPOINT}/v1/graphql`;
const httpURL = `${scheme("https")}://${GRAPHQL_ENDPOINT}/v1/graphql`;
const splitter = ({ query }) => {
const { kind, operation } = getMainDefinition(query) || {};
const isSubscription =
kind === "OperationDefinition" && operation === "subscription";
return isSubscription;
};
const cache = new InMemoryCache();
const options = { reconnect: true };
const wsLink = new GraphQLWsLink(createClient({ url: wsURI, connectionParams: { options } }));
const httpLink = new HttpLink({ uri: httpURL });
const link = split(splitter, wsLink, httpLink);
const client = new ApolloClient({ link, cache });
export default client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment