Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
794 lines (673 sloc) 33.6 KB

Step 10: Live updates with GraphQL subscriptions

So far we've been developing the app and we've been treating it as if there's no other users; we're the only one exists. This approach is true when we want to develop a UI and focus on UX, but comes a point where we need to start thinking on a macro level. Our app is social interactive, and if things work properly for me, it doesn't mean that it works properly to the fellow I'm chatting with. It's inevitable to have an authentication system in our app, hence we need to take care of things before we get to that stage.

Try to open 2 instances of the app in 2 separate tabs/windows, and navigate into the same chat room. Try to send a message with one instance and notice that the second instance doesn't update unless we refresh the page.

ezgif com-video-to-gif (2)

This issue is very important and should be addressed, because a chat is all about sending and receiving messages on a lively basis. This issue was expected, as there's no mechanism that would trigger and listen to changes in the back-end. In this chapter we're gonna address that issue by implementing exactly that mechanism.

Introducing: GraphQL Subscriptions

GraphQL subscriptions is a mechanism that works on web-sockets and live communication; clients can subscribe to it and be notified regards specific changes that happen in the back-end. Notifications will be triggered manually by us and can be provided with parameters that provide additional information regards the triggered event. For example, a messageAdded will be published with the new message, and will notify all clients who are subscribed to that event. Once the subscribers are notified, they can respond as they would like to, such as updating the UI.

subscription-notifications

A subscription is presented in our GraphQL schema as a separate type called Subscription, where each field represents an event name along with its return type. Like any other GraphQL type, each field should be match with a resolver where we handle the request.

In this chapter we will implement the messageAdded subscription, so users can be notified when it happens and update the messages list to contain the new message.

Implementing a subscription

We will start by creating a new Subscription type in our GraphQL schema with the field messageAdded:

Server Step 7.1: Add subscription type with messageAdded

Changed schema/typeDefs.graphql
@@ -22,3 +22,7 @@
 ┊22┊22┊type Mutation {
 ┊23┊23┊  addMessage(chatId: ID!, content: String!): Message
 ┊24┊24┊}
+┊  ┊25┊
+┊  ┊26┊type Subscription {
+┊  ┊27┊  messageAdded: Message!
+┊  ┊28┊}

Changes are triggered using an event-emitter like object called PubSub. This can be done using the PubSub.prototype.publish method. We will create a new instance of it and will provide it via the context - a common pattern for providing objects which are useful for the execution of the resolvers:

TODO: Explain what the context is

Server Step 7.2: Provide a new instance of PubSub to context

Changed index.ts
@@ -1,4 +1,4 @@
-┊1┊ ┊import { ApolloServer, gql } from 'apollo-server-express';
+┊ ┊1┊import { ApolloServer, gql, PubSub } from 'apollo-server-express';
 ┊2┊2┊import bodyParser from 'body-parser';
 ┊3┊3┊import cors from 'cors';
 ┊4┊4┊import express from 'express';
@@ -13,7 +13,11 @@
 ┊13┊13┊  res.send('pong');
 ┊14┊14┊});
 ┊15┊15┊
-┊16┊  ┊const server = new ApolloServer({ schema });
+┊  ┊16┊const pubsub = new PubSub();
+┊  ┊17┊const server = new ApolloServer({
+┊  ┊18┊  schema,
+┊  ┊19┊  context: () => ({ pubsub }),
+┊  ┊20┊});
 ┊17┊21┊
 ┊18┊22┊server.applyMiddleware({
 ┊19┊23┊  app,

Inside the addMessage resolver we will publish a new event called messageAdded. The 3rd argument of the resolver will be the context object that we've just defined in the previous step, where we can use the pubsub instance. The TypeScript type of our context can be directly defined and generated by CodeGen through the codegen.yml file. This can be specified under the ContextType field with the file path that contains the context followed by the name of the exported object, like so:

Server Step 7.3: Define Context type

Changed codegen.yml
@@ -6,6 +6,7 @@
 ┊ 6┊ 6┊      - typescript
 ┊ 7┊ 7┊      - typescript-resolvers
 ┊ 8┊ 8┊    config:
+┊  ┊ 9┊      contextType: ../context#MyContext
 ┊ 9┊10┊      mappers:
 ┊10┊11┊        # import { Message } from '../db'
 ┊11┊12┊        # The root types of Message resolvers
Added context.ts
@@ -0,0 +1,5 @@
+┊ ┊1┊import { PubSub } from 'apollo-server-express';
+┊ ┊2┊
+┊ ┊3┊export type MyContext = {
+┊ ┊4┊  pubsub: PubSub;
+┊ ┊5┊};

The event will be published right after the message was pushed into the messages collection, because order is a crucial thing. We don't want to notify our users unless the change has been made. The event will have a single parameter which represents the new message.

Server Step 7.4: Publish message added event

Changed schema/resolvers.ts
@@ -28,7 +28,7 @@
 ┊28┊28┊  },
 ┊29┊29┊
 ┊30┊30┊  Mutation: {
-┊31┊  ┊    addMessage(root, { chatId, content }) {
+┊  ┊31┊    addMessage(root, { chatId, content }, { pubsub }) {
 ┊32┊32┊      const chatIndex = chats.findIndex(c => c.id === chatId);
 ┊33┊33┊
 ┊34┊34┊      if (chatIndex === -1) return null;
@@ -48,6 +48,10 @@
 ┊48┊48┊      chats.splice(chatIndex, 1);
 ┊49┊49┊      chats.unshift(chat);
 ┊50┊50┊
+┊  ┊51┊      pubsub.publish('messageAdded', {
+┊  ┊52┊        messageAdded: message,
+┊  ┊53┊      });
+┊  ┊54┊
 ┊51┊55┊      return message;
 ┊52┊56┊    },
 ┊53┊57┊  },
Changed tests/mutations/addMessage.test.ts
@@ -1,5 +1,5 @@
 ┊1┊1┊import { createTestClient } from 'apollo-server-testing';
-┊2┊ ┊import { ApolloServer, gql } from 'apollo-server-express';
+┊ ┊2┊import { ApolloServer, PubSub, gql } from 'apollo-server-express';
 ┊3┊3┊import schema from '../../schema';
 ┊4┊4┊import { resetDb } from '../../db';
 ┊5┊5┊
@@ -7,7 +7,10 @@
 ┊ 7┊ 7┊  beforeEach(resetDb);
 ┊ 8┊ 8┊
 ┊ 9┊ 9┊  it('should add message to specified chat', async () => {
-┊10┊  ┊    const server = new ApolloServer({ schema });
+┊  ┊10┊    const server = new ApolloServer({
+┊  ┊11┊      schema,
+┊  ┊12┊      context: () => ({ pubsub: new PubSub() }),
+┊  ┊13┊    });
 ┊11┊14┊
 ┊12┊15┊    const { query, mutate } = createTestClient(server);

A subscription resolver behaves differently and thus should be implemented differently. Using the pubsub.asyncIterator instance, we can specify which events are relevant for the subscription, for example, all clients who are subscribers of the chatUpdated subscription will be notified when messageAdded, messageRemoved and chatInfoChanged events were triggered. For now, we will have a 1 to 1 relationship between the messageAdded event and messageAdded subscription. In code, it should look like this:

Server Step 7.5: Add Subscription.messageAdded resolver

Changed schema/resolvers.ts
@@ -55,6 +55,13 @@
 ┊55┊55┊      return message;
 ┊56┊56┊    },
 ┊57┊57┊  },
+┊  ┊58┊
+┊  ┊59┊  Subscription: {
+┊  ┊60┊    messageAdded: {
+┊  ┊61┊      subscribe: (root, args, { pubsub }) =>
+┊  ┊62┊        pubsub.asyncIterator('messageAdded'),
+┊  ┊63┊    },
+┊  ┊64┊  },
 ┊58┊65┊};
 ┊59┊66┊
 ┊60┊67┊export default resolvers;

The idea behind the pubsub.asyncIterator method is that it returns an Iterator like object, where each value is a promise that will be resolved when the relevant events are triggered. By default, the parameter that has a similar name to the subscription will be returned as a response, e.g. messageAdded parameter will be sent back to the subscribers. This behavior can be modified as explained here, but it's very unlikely and not necessary for our use case.

As mentioned at the beginning of this article, there needs to be an open connection between the client and the server so live updates can happen. There are serveral methods for doing so, but the 2 most popular ones are:

  • Based on polling with HTTP protocol
  • Based on web-sockets (WS protocol)

HTTP polling means that each amount of time an HTTP request will be made to the server where potential changes can be sent back to us at any given time. HTTP requests are very reliable, but the problem with them is that they contain a lot of information in their headers, so even if we sent an empty request, it might be still very heavy due to cookies, user-agent, language, request type, etc.

With web-sockets, once a connection has been established, it will remain open and it will only send the information which is relevant for the current session, so it's much faster. The communication is between the server and the client is bi-directional when it comes to web-sockets, which means that a user can spontaneously receive information from the server, as long as the communication channel remains open.

More information about the advantages of Web Sockets over HTTP can be found at websocket.org

The subscription mechanism can be installed using the server.installSubscriptionHandlers. It will use the WS protocol by default and will fallback to HTTP polling if there were troubles establishing a connection via WS protocol:

Server Step 7.6: Install subscription handlers

Changed index.ts
@@ -2,6 +2,7 @@
 ┊2┊2┊import bodyParser from 'body-parser';
 ┊3┊3┊import cors from 'cors';
 ┊4┊4┊import express from 'express';
+┊ ┊5┊import http from 'http';
 ┊5┊6┊import schema from './schema';
 ┊6┊7┊
 ┊7┊8┊const app = express();
@@ -24,8 +25,11 @@
 ┊24┊25┊  path: '/graphql',
 ┊25┊26┊});
 ┊26┊27┊
+┊  ┊28┊const httpServer = http.createServer(app);
+┊  ┊29┊server.installSubscriptionHandlers(httpServer);
+┊  ┊30┊
 ┊27┊31┊const port = process.env.PORT || 4000;
 ┊28┊32┊
-┊29┊  ┊app.listen(port, () => {
+┊  ┊33┊httpServer.listen(port, () => {
 ┊30┊34┊  console.log(`Server is listening on port ${port}`);
 ┊31┊35┊});

Now we have everything set and we can start listening to subscriptions and react to to triggered changes.

Using subscriptions

To support subscriptions we need to establish a WS connection. For that we will need to update our Apollo client. We will install a couple of packages that will enable such feature:

$ yarn add subscriptions-transport-ws apollo-link apollo-link-ws apollo-utilities
  • subscriptions-transport-ws - a transport layer that understands how client and GraphQL API communicates with each other. The spec has GQL_INIT GQL_UPDATE GQL_DATA events.
  • apollo-link-ws - Will establish a WS connection.
  • apollo-link - Will enable WS and HTTP connections co-exist in a single client.
  • apollo-utilities - Includes utility functions that will help us analyze a GraphQL AST.

The WS url can be composed by simply running a regular expression over the REACT_APP_SERVER_URL environment variable and is unnecessary to be stored separately. Here's how our new client should look like: \

Client Step 10.1: Setup WS link

Changed src/client.ts
@@ -1,16 +1,40 @@
 ┊ 1┊ 1┊import { InMemoryCache } from 'apollo-cache-inmemory';
 ┊ 2┊ 2┊import { ApolloClient } from 'apollo-client';
+┊  ┊ 3┊import { getMainDefinition } from 'apollo-utilities';
 ┊ 3┊ 4┊import { HttpLink } from 'apollo-link-http';
+┊  ┊ 5┊import { WebSocketLink } from 'apollo-link-ws';
+┊  ┊ 6┊import { ApolloLink, split } from 'apollo-link';
 ┊ 4┊ 7┊
 ┊ 5┊ 8┊const httpUri = process.env.REACT_APP_SERVER_URL + '/graphql';
+┊  ┊ 9┊const wsUri = httpUri.replace(/^https?/, 'ws');
 ┊ 6┊10┊
 ┊ 7┊11┊const httpLink = new HttpLink({
 ┊ 8┊12┊  uri: httpUri,
 ┊ 9┊13┊});
 ┊10┊14┊
+┊  ┊15┊const wsLink = new WebSocketLink({
+┊  ┊16┊  uri: wsUri,
+┊  ┊17┊  options: {
+┊  ┊18┊    // Automatic reconnect in case of connection error
+┊  ┊19┊    reconnect: true,
+┊  ┊20┊  },
+┊  ┊21┊});
+┊  ┊22┊
+┊  ┊23┊const terminatingLink = split(
+┊  ┊24┊  ({ query }) => {
+┊  ┊25┊    const { kind, operation } = getMainDefinition(query);
+┊  ┊26┊    // If this is a subscription query, use wsLink, otherwise use httpLink
+┊  ┊27┊    return kind === 'OperationDefinition' && operation === 'subscription';
+┊  ┊28┊  },
+┊  ┊29┊  wsLink,
+┊  ┊30┊  httpLink
+┊  ┊31┊);
+┊  ┊32┊
+┊  ┊33┊const link = ApolloLink.from([terminatingLink]);
+┊  ┊34┊
 ┊11┊35┊const inMemoryCache = new InMemoryCache();
 ┊12┊36┊
 ┊13┊37┊export default new ApolloClient({
-┊14┊  ┊  link: httpLink,
+┊  ┊38┊  link,
 ┊15┊39┊  cache: inMemoryCache,
 ┊16┊40┊});

Our subscription listeners should live globally across our application and shouldn't be bound to a specific component, thus we will create an external service which will be responsible of doing so. Using that service, we will update our GraphQL data-store any time a new message has been added. We will define a messageAdded subscription in a dedicated file under the src/graphql/subscriptions dir where all our subscriptions will be defined and exported:

TODO: - but they are anyway. It’s just a standalone function that is used in a component. Which makes no difference.

Client Step 10.2: Add messageAdded subscription document

Added src/graphql/subscriptions/index.ts
@@ -0,0 +1 @@
+┊ ┊1┊export { default as messageAdded } from './messageAdded.subscription';
Added src/graphql/subscriptions/messageAdded.subscription.ts
@@ -0,0 +1,11 @@
+┊  ┊ 1┊import gql from 'graphql-tag';
+┊  ┊ 2┊import * as fragments from '../fragments';
+┊  ┊ 3┊
+┊  ┊ 4┊export default gql`
+┊  ┊ 5┊  subscription MessageAdded {
+┊  ┊ 6┊    messageAdded {
+┊  ┊ 7┊      ...Message
+┊  ┊ 8┊    }
+┊  ┊ 9┊  }
+┊  ┊10┊  ${fragments.message}
+┊  ┊11┊`;

Now we will create the service under the path services/cache.service.ts. Like any other GraphQL operation, react-apollo-hooks provides us with a dedicated React hook for subscriptions called useSubscription. Given the subscription document and the onSubscriptionData callback we can handle incoming changes. We will be using GraphQL Code Generator to generate typed subscription hooks, as the typescript-react-apollo plug-in supports it right out of the box. First let's update the codegen.yml file to look for documents in the graphql/subscriptions dir:

Client Step 10.3: Include subscription documents in codegen.yml

Changed codegen.yml
@@ -3,6 +3,7 @@
 ┊3┊3┊  - ./src/components/**/*.tsx
 ┊4┊4┊  - ./src/graphql/fragments/**/*.ts
 ┊5┊5┊  - ./src/graphql/queries/**/*.ts
+┊ ┊6┊  - ./src/graphql/subscriptions/**/*.ts
 ┊6┊7┊overwrite: true
 ┊7┊8┊generates:
 ┊8┊9┊  ./src/graphql/types.tsx:

And then we will type the code generation command:

$ npm run codegen

Now we can import and use the newly generated hook useMessageAddedSubscription in the cache.service. Like mentioned earlier, we will be using the onSubscriptionData callback to retrieve the change that was sent by the server and we will use it to re-write our cache. In this case we will be writing a new fragment for the incoming message, and we will update the correlated chat:

Client Step 10.4: Update cache on message added

Added src/services/cache.service.ts
@@ -0,0 +1,86 @@
+┊  ┊ 1┊import { DataProxy } from 'apollo-cache';
+┊  ┊ 2┊import { defaultDataIdFromObject } from 'apollo-cache-inmemory';
+┊  ┊ 3┊import { ApolloClient } from 'apollo-client';
+┊  ┊ 4┊import * as fragments from '../graphql/fragments';
+┊  ┊ 5┊import * as queries from '../graphql/queries';
+┊  ┊ 6┊import { MessageFragment, useMessageAddedSubscription } from '../graphql/types';
+┊  ┊ 7┊
+┊  ┊ 8┊type Client = ApolloClient<any> | DataProxy;
+┊  ┊ 9┊
+┊  ┊10┊export const useCacheService = () => {
+┊  ┊11┊  useMessageAddedSubscription({
+┊  ┊12┊    onSubscriptionData: ({ client, subscriptionData: { data } }) => {
+┊  ┊13┊      if (data) {
+┊  ┊14┊        writeMessage(client, data.messageAdded);
+┊  ┊15┊      }
+┊  ┊16┊    },
+┊  ┊17┊  });
+┊  ┊18┊};
+┊  ┊19┊
+┊  ┊20┊export const writeMessage = (client: Client, message: MessageFragment) => {
+┊  ┊21┊  type FullChat = { [key: string]: any };
+┊  ┊22┊  let fullChat;
+┊  ┊23┊
+┊  ┊24┊  const chatIdFromStore = defaultDataIdFromObject(message.chat);
+┊  ┊25┊
+┊  ┊26┊  if (chatIdFromStore === null) {
+┊  ┊27┊    return;
+┊  ┊28┊  }
+┊  ┊29┊  try {
+┊  ┊30┊    fullChat = client.readFragment<FullChat>({
+┊  ┊31┊      id: chatIdFromStore,
+┊  ┊32┊      fragment: fragments.fullChat,
+┊  ┊33┊      fragmentName: 'FullChat',
+┊  ┊34┊    });
+┊  ┊35┊  } catch (e) {
+┊  ┊36┊    return;
+┊  ┊37┊  }
+┊  ┊38┊
+┊  ┊39┊  if (fullChat === null || fullChat.messages === null) {
+┊  ┊40┊    return;
+┊  ┊41┊  }
+┊  ┊42┊  if (fullChat.messages.some((m: any) => m.id === message.id)) return;
+┊  ┊43┊
+┊  ┊44┊  fullChat.messages.push(message);
+┊  ┊45┊  fullChat.lastMessage = message;
+┊  ┊46┊
+┊  ┊47┊  client.writeFragment({
+┊  ┊48┊    id: chatIdFromStore,
+┊  ┊49┊    fragment: fragments.fullChat,
+┊  ┊50┊    fragmentName: 'FullChat',
+┊  ┊51┊    data: fullChat,
+┊  ┊52┊  });
+┊  ┊53┊
+┊  ┊54┊  let data;
+┊  ┊55┊  try {
+┊  ┊56┊    data = client.readQuery({
+┊  ┊57┊      query: queries.chats,
+┊  ┊58┊    });
+┊  ┊59┊  } catch (e) {
+┊  ┊60┊    return;
+┊  ┊61┊  }
+┊  ┊62┊
+┊  ┊63┊  if (!data || data === null) {
+┊  ┊64┊    return null;
+┊  ┊65┊  }
+┊  ┊66┊  if (!data.chats || data.chats === undefined) {
+┊  ┊67┊    return null;
+┊  ┊68┊  }
+┊  ┊69┊  const chats = data.chats;
+┊  ┊70┊
+┊  ┊71┊  const chatIndex = chats.findIndex((c: any) => {
+┊  ┊72┊    if (message === null || message.chat === null) return -1;
+┊  ┊73┊    return c.id === message.chat.id;
+┊  ┊74┊  });
+┊  ┊75┊  if (chatIndex === -1) return;
+┊  ┊76┊  const chatWhereAdded = chats[chatIndex];
+┊  ┊77┊
+┊  ┊78┊  // The chat will appear at the top of the ChatsList component
+┊  ┊79┊  chats.splice(chatIndex, 1);
+┊  ┊80┊  chats.unshift(chatWhereAdded);
+┊  ┊81┊
+┊  ┊82┊  client.writeQuery({
+┊  ┊83┊    query: queries.chats,
+┊  ┊84┊    data: { chats: chats },
+┊  ┊85┊  });
+┊  ┊86┊};

We will also use the exported writeMessage() function in the ChatRoomScreen so we won't have any code duplications:

Client Step 10.4: Update cache on message added

Changed src/components/ChatRoomScreen/index.tsx
@@ -1,4 +1,3 @@
-┊1┊ ┊import { defaultDataIdFromObject } from 'apollo-cache-inmemory';
 ┊2┊1┊import gql from 'graphql-tag';
 ┊3┊2┊import React from 'react';
 ┊4┊3┊import { useCallback } from 'react';
@@ -7,9 +6,9 @@
 ┊ 7┊ 6┊import MessageInput from './MessageInput';
 ┊ 8┊ 7┊import MessagesList from './MessagesList';
 ┊ 9┊ 8┊import { History } from 'history';
-┊10┊  ┊import { ChatsQuery, useGetChatQuery, useAddMessageMutation } from '../../graphql/types';
-┊11┊  ┊import * as queries from '../../graphql/queries';
+┊  ┊ 9┊import { useGetChatQuery, useAddMessageMutation } from '../../graphql/types';
 ┊12┊10┊import * as fragments from '../../graphql/fragments';
+┊  ┊11┊import { writeMessage } from '../../services/cache.service';
 ┊13┊12┊
 ┊14┊13┊const Container = styled.div`
 ┊15┊14┊  background: url(/assets/chat-background.jpg);
@@ -43,10 +42,6 @@
 ┊43┊42┊  history: History;
 ┊44┊43┊}
 ┊45┊44┊
-┊46┊  ┊interface ChatsResult {
-┊47┊  ┊  chats: any[];
-┊48┊  ┊}
-┊49┊  ┊
 ┊50┊45┊const ChatRoomScreen: React.FC<ChatRoomScreenParams> = ({
 ┊51┊46┊  history,
 ┊52┊47┊  chatId,
@@ -79,68 +74,7 @@
 ┊ 79┊ 74┊          },
 ┊ 80┊ 75┊        },
 ┊ 81┊ 76┊        update: (client, { data: { addMessage } }) => {
-┊ 82┊   ┊          type FullChat = { [key: string]: any };
-┊ 83┊   ┊          let fullChat;
-┊ 84┊   ┊
-┊ 85┊   ┊          const chatIdFromStore = defaultDataIdFromObject(addMessage.chat);
-┊ 86┊   ┊
-┊ 87┊   ┊          if (chatIdFromStore === null) {
-┊ 88┊   ┊            return;
-┊ 89┊   ┊          }
-┊ 90┊   ┊          try {
-┊ 91┊   ┊            fullChat = client.readFragment<FullChat>({
-┊ 92┊   ┊              id: chatIdFromStore,
-┊ 93┊   ┊              fragment: fragments.fullChat,
-┊ 94┊   ┊              fragmentName: 'FullChat',
-┊ 95┊   ┊            });
-┊ 96┊   ┊          } catch (e) {
-┊ 97┊   ┊            return;
-┊ 98┊   ┊          }
-┊ 99┊   ┊
-┊100┊   ┊          if (fullChat === null || fullChat.messages === null) {
-┊101┊   ┊            return;
-┊102┊   ┊          }
-┊103┊   ┊          if (fullChat.messages.messages.some((m: any) => m.id === addMessage.id)) return;
-┊104┊   ┊
-┊105┊   ┊          fullChat.messages.messages.push(addMessage);
-┊106┊   ┊          fullChat.lastMessage = addMessage;
-┊107┊   ┊
-┊108┊   ┊          client.writeFragment({
-┊109┊   ┊            id: chatIdFromStore,
-┊110┊   ┊            fragment: fragments.fullChat,
-┊111┊   ┊            fragmentName: 'FullChat',
-┊112┊   ┊            data: fullChat,
-┊113┊   ┊          });
-┊114┊   ┊
-┊115┊   ┊          let data: ChatsQuery | null;
-┊116┊   ┊          try {
-┊117┊   ┊            data = client.readQuery({
-┊118┊   ┊              query: queries.chats,
-┊119┊   ┊            });
-┊120┊   ┊          } catch (e) {
-┊121┊   ┊            return;
-┊122┊   ┊          }
-┊123┊   ┊
-┊124┊   ┊          if (!data || !data.chats) {
-┊125┊   ┊            return null;
-┊126┊   ┊          }
-┊127┊   ┊          const chats = data.chats;
-┊128┊   ┊
-┊129┊   ┊          const chatIndex = chats.findIndex((c: any) => {
-┊130┊   ┊            if (addMessage === null || addMessage.chat === null) return -1;
-┊131┊   ┊            return c.id === addMessage.chat.id;
-┊132┊   ┊          });
-┊133┊   ┊          if (chatIndex === -1) return;
-┊134┊   ┊          const chatWhereAdded = chats[chatIndex];
-┊135┊   ┊
-┊136┊   ┊          // The chat will appear at the top of the ChatsList component
-┊137┊   ┊          chats.splice(chatIndex, 1);
-┊138┊   ┊          chats.unshift(chatWhereAdded);
-┊139┊   ┊
-┊140┊   ┊          client.writeQuery({
-┊141┊   ┊            query: queries.chats,
-┊142┊   ┊            data: { chats: chats },
-┊143┊   ┊          });
+┊   ┊ 77┊          writeMessage(client, addMessage);
 ┊144┊ 78┊        },
 ┊145┊ 79┊      });
 ┊146┊ 80┊    },

One thing missing that you might notice is that we're trying to retrieve the chat from the received message, unfortunately our GraphQL schema doesn't support it and we will need to add it. On the server, we will add a chat field to the Message type in the GraphQL schema, and we will implement a resolver which will lookup for the chat in the chats collection:

Server Step 7.7: Add Message.chat resolver

Changed schema/resolvers.ts
@@ -5,6 +5,12 @@
 ┊ 5┊ 5┊const resolvers: Resolvers = {
 ┊ 6┊ 6┊  Date: GraphQLDateTime,
 ┊ 7┊ 7┊
+┊  ┊ 8┊  Message: {
+┊  ┊ 9┊    chat(message) {
+┊  ┊10┊      return chats.find(c => c.messages.some(m => m === message.id)) || null;
+┊  ┊11┊    },
+┊  ┊12┊  },
+┊  ┊13┊
 ┊ 8┊14┊  Chat: {
 ┊ 9┊15┊    messages(chat) {
 ┊10┊16┊      return messages.filter(m => chat.messages.includes(m.id));
Changed schema/typeDefs.graphql
@@ -4,6 +4,7 @@
 ┊ 4┊ 4┊  id: ID!
 ┊ 5┊ 5┊  content: String!
 ┊ 6┊ 6┊  createdAt: Date!
+┊  ┊ 7┊  chat: Chat
 ┊ 7┊ 8┊}
 ┊ 8┊ 9┊
 ┊ 9┊10┊type Chat {

Now that we have it supported we can update the Message fragment in the client to include that information. We don't need the entire chat, only its ID, since the fragment ID composition is done out of an ID and type name:

Client Step 10.5: Add chat.id to message fragment

Changed src/components/ChatRoomScreen/index.tsx
@@ -70,6 +70,10 @@
 ┊70┊70┊              .toString(36)
 ┊71┊71┊              .substr(2, 9),
 ┊72┊72┊            createdAt: new Date(),
+┊  ┊73┊            chat: {
+┊  ┊74┊              __typename: 'Chat',
+┊  ┊75┊              id: chatId,
+┊  ┊76┊            },
 ┊73┊77┊            content,
 ┊74┊78┊          },
 ┊75┊79┊        },
Changed src/components/ChatsListScreen/ChatsList.test.tsx
@@ -36,6 +36,10 @@
 ┊36┊36┊                  id: 1,
 ┊37┊37┊                  content: 'Hello',
 ┊38┊38┊                  createdAt: new Date('1 Jan 2019 GMT'),
+┊  ┊39┊                  chat: {
+┊  ┊40┊                    __typename: 'Chat',
+┊  ┊41┊                    id: 1,
+┊  ┊42┊                  },
 ┊39┊43┊                },
 ┊40┊44┊              },
 ┊41┊45┊            ],
@@ -82,6 +86,10 @@
 ┊82┊86┊                  id: 1,
 ┊83┊87┊                  content: 'Hello',
 ┊84┊88┊                  createdAt: new Date('1 Jan 2019 GMT'),
+┊  ┊89┊                  chat: {
+┊  ┊90┊                    __typename: 'Chat',
+┊  ┊91┊                    id: 1,
+┊  ┊92┊                  },
 ┊85┊93┊                },
 ┊86┊94┊              },
 ┊87┊95┊            ],
Changed src/graphql/fragments/message.fragment.ts
@@ -5,5 +5,8 @@
 ┊ 5┊ 5┊    id
 ┊ 6┊ 6┊    createdAt
 ┊ 7┊ 7┊    content
+┊  ┊ 8┊    chat {
+┊  ┊ 9┊      id
+┊  ┊10┊    }
 ┊ 8┊11┊  }
 ┊ 9┊12┊`;

Finally, we will import the useCacheService React hook that we've just created and we will use it in our main App component. This means that the cache service will start listening for changes right as the app component is mounted:

Client Step 10.6: Use cache service

Changed src/App.test.tsx
@@ -3,9 +3,15 @@
 ┊ 3┊ 3┊import ReactDOM from 'react-dom';
 ┊ 4┊ 4┊import App from './App';
 ┊ 5┊ 5┊import { mockApolloClient } from './test-helpers';
+┊  ┊ 6┊import * as subscriptions from './graphql/subscriptions';
 ┊ 6┊ 7┊
 ┊ 7┊ 8┊it('renders without crashing', () => {
-┊ 8┊  ┊  const client = mockApolloClient();
+┊  ┊ 9┊  const client = mockApolloClient([
+┊  ┊10┊    {
+┊  ┊11┊      request: { query: subscriptions.messageAdded },
+┊  ┊12┊      result: { data: {} }
+┊  ┊13┊    }
+┊  ┊14┊  ]);
 ┊ 9┊15┊  const div = document.createElement('div');
 ┊10┊16┊
 ┊11┊17┊  ReactDOM.render(
Changed src/App.tsx
@@ -8,26 +8,31 @@
 ┊ 8┊ 8┊import ChatRoomScreen from './components/ChatRoomScreen';
 ┊ 9┊ 9┊import ChatsListScreen from './components/ChatsListScreen';
 ┊10┊10┊import AnimatedSwitch from './components/AnimatedSwitch';
+┊  ┊11┊import { useCacheService } from './services/cache.service';
 ┊11┊12┊
-┊12┊  ┊const App: React.FC = () => (
-┊13┊  ┊  <BrowserRouter>
-┊14┊  ┊    <AnimatedSwitch>
-┊15┊  ┊      <Route exact path="/chats" component={ChatsListScreen} />
+┊  ┊13┊const App: React.FC = () => {
+┊  ┊14┊  useCacheService();
 ┊16┊15┊
-┊17┊  ┊      <Route
-┊18┊  ┊        exact
-┊19┊  ┊        path="/chats/:chatId"
-┊20┊  ┊        component={({
-┊21┊  ┊          match,
-┊22┊  ┊          history,
-┊23┊  ┊        }: RouteComponentProps<{ chatId: string }>) => (
-┊24┊  ┊          <ChatRoomScreen chatId={match.params.chatId} history={history} />
-┊25┊  ┊        )}
-┊26┊  ┊      />
-┊27┊  ┊    </AnimatedSwitch>
-┊28┊  ┊    <Route exact path="/" render={redirectToChats} />
-┊29┊  ┊  </BrowserRouter>
-┊30┊  ┊);
+┊  ┊16┊  return (
+┊  ┊17┊    <BrowserRouter>
+┊  ┊18┊      <AnimatedSwitch>
+┊  ┊19┊        <Route exact path="/chats" component={ChatsListScreen} />
+┊  ┊20┊
+┊  ┊21┊        <Route
+┊  ┊22┊          exact
+┊  ┊23┊          path="/chats/:chatId"
+┊  ┊24┊          component={({
+┊  ┊25┊            match,
+┊  ┊26┊            history,
+┊  ┊27┊          }: RouteComponentProps<{ chatId: string }>) => (
+┊  ┊28┊            <ChatRoomScreen chatId={match.params.chatId} history={history} />
+┊  ┊29┊          )}
+┊  ┊30┊        />
+┊  ┊31┊      </AnimatedSwitch>
+┊  ┊32┊      <Route exact path="/" render={redirectToChats} />
+┊  ┊33┊    </BrowserRouter>
+┊  ┊34┊  );
+┊  ┊35┊};
 ┊31┊36┊
 ┊32┊37┊const redirectToChats = () => <Redirect to="/chats" />;

Subscription handling is complete! If you'll try to repeat the same process again where you check messages updating between 2 instances of the app, you should see them both update.


TODO: useCacheService shouldn’t be called like that since it’s related to message events and cache updates are only side-effects.

< Previous Step Next Step >
You can’t perform that action at this time.