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 Jul 20, 2019
1 parent 7a9ef37 commit 8686853
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
"apollo-link-http": "1.5.15",
"apollo-link-mock": "1.0.1",
"graphql": "14.4.2",
"apollo-link-ws": "1.0.18",
"apollo-utilities": "1.3.2",
"graphql-tag": "2.10.1",
"history": "4.9.0",
"moment": "2.24.0",
Expand All @@ -40,6 +42,7 @@
"react-router-transition": "1.3.0",
"react-scripts": "3.0.1",
"styled-components": "4.3.2",
"subscriptions-transport-ws": "0.9.16",
"typescript": "3.5.3"
},
"scripts": {
Expand Down
26 changes: 25 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,40 @@
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,
},
});

const terminatingLink = split(
({ query }) => {
const { kind, operation } = 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 8686853

Please sign in to comment.