Im using Graphcool’s backend as a service. Im new to GraphQL in general so I don’t know if this is a common issue or not, but Im finding subscriptions to be flaky. Normal queries on the other hand work fine.
On the page that uses a subscription about half of the time I get this error in my browser console:
WebSocket connection to ‘wss://subscriptions.graph.cool/v1/PROJECT-ID’ failed: WebSocket is closed before the connection is established.
When I get the error my subscription does’t work. If I refresh the page a few times then it works again. I am in Thailand but I’m at a co-working space and the internet seems fine for everything else.
Even if intermittent this is a major issue for me as I’m using a subscription to update facebook style comments on a page. So when it doesn’t work the user can’t see they’ve left a comment, meaning they’ll either comment again or think that comments don’t work.
Im not sure if this is a Graphcool or Apollo issue, but is there a way to make Apollo continuously try and reconnect to the subscription endpoint if there is an issue?
This is what my index JS file has:
const wsLink = new WebSocketLink({
uri: `wss://subscriptions.graph.cool/v1/PROJECT-ID`,
options: {
reconnect: true,
},
});
const httpLink = new HttpLink({
uri: 'https://api.graph.cool/simple/v1/PROJECT-ID',
});
// auth
const middlewareAuthLink = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('auth-token');
const authorizationHeader = token ? `Bearer ${token}` : null;
operation.setContext({
headers: {
authorization: authorizationHeader,
},
});
return forward(operation);
});
const cache = new InMemoryCache();
// @TODO Remote local state stuff
const defaultState = {
CurrentUserIsLoggedIn: {
__typename: 'CurrentUserIsLoggedIn',
value: false,
},
};
const stateLink = withClientState({
cache,
defaults: defaultState,
resolvers: {
Mutation: {
CurrentUserIsLoggedIn: (_, args) => {
const data = {
CurrentUserIsLoggedIn: {
__typename: 'CurrentUserIsLoggedIn',
value: args.value,
},
};
cache.writeData({ data });
},
},
},
});
const client = new ApolloClient({
cache,
link: ApolloLink.from([
stateLink,
middlewareAuthLink,
split(
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink,
),
]),
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'),
);