From 88f09c024aa2402237bb3fdaeac7409673319290 Mon Sep 17 00:00:00 2001 From: DAB0mB Date: Wed, 27 Mar 2019 01:25:31 +0800 Subject: [PATCH] Step 10.1: Setup WS link --- package.json | 3 +++ src/client.ts | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 24268090f..26755f262 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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": { diff --git a/src/client.ts b/src/client.ts index a0df9cdf7..0cf61255a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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, });