Skip to content

Commit

Permalink
Step 10.1: Setup WS link
Browse files Browse the repository at this point in the history
  • Loading branch information
DAB0mB authored and Urigo committed May 20, 2020
1 parent ca613e1 commit 88f09c0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
"apollo-link": "1.2.14",
"apollo-link-http": "1.5.17",
"apollo-link-mock": "1.0.1",
"apollo-link-ws": "1.0.20",
"apollo-utilities": "1.3.4",
"graphql": "15.0.0",
"graphql-tag": "2.10.3",
"history": "4.10.1",
Expand All @@ -43,6 +45,7 @@
"react-router-transition": "2.0.0",
"react-scripts": "3.4.1",
"styled-components": "5.1.0",
"subscriptions-transport-ws": "0.9.16",
"typescript": "3.9.3"
},
"scripts": {
Expand Down
34 changes: 33 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { getMainDefinition } from 'apollo-utilities';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { ApolloLink, split } from 'apollo-link';

const httpUri = process.env.REACT_APP_SERVER_URL + '/graphql';
const wsUri = httpUri.replace(/^https?/, 'ws');

const httpLink = new HttpLink({
uri: httpUri,
});

const wsLink = new WebSocketLink({
uri: wsUri,
options: {
// Automatic reconnect in case of connection error
reconnect: true,
},
});

/**
* Fix error typing in `split` method in `apollo-link`
* Related issue https://github.com/apollographql/apollo-client/issues/3090
*/
export interface Definition {
kind: string;
operation?: string;
}
const terminatingLink = split(
({ query }) => {
const { kind, operation }: Definition = getMainDefinition(query);
// If this is a subscription query, use wsLink, otherwise use httpLink
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink
);

const link = ApolloLink.from([terminatingLink]);

const inMemoryCache = new InMemoryCache();

export default new ApolloClient({
link: httpLink,
link,
cache: inMemoryCache,
});

0 comments on commit 88f09c0

Please sign in to comment.