summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/actioncable_link.js
blob: cf53d9e21b4a7592e30fbbdfbd1ec4c18b2ef7e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { ApolloLink, Observable } from '@apollo/client/core';
import { print } from 'graphql';
import cable from '~/actioncable_consumer';
import { uuids } from '~/lib/utils/uuids';

export default class ActionCableLink extends ApolloLink {
  // eslint-disable-next-line class-methods-use-this
  request(operation) {
    return new Observable((observer) => {
      const subscription = cable.subscriptions.create(
        {
          channel: 'GraphqlChannel',
          query: operation.query ? print(operation.query) : null,
          variables: operation.variables,
          operationName: operation.operationName,
          nonce: uuids()[0],
        },
        {
          received(data) {
            if (data.errors) {
              observer.error(data.errors);
            } else if (data.result) {
              observer.next(data.result);
            }

            if (!data.more) {
              observer.complete();
            }
          },
        },
      );

      return {
        unsubscribe() {
          subscription.unsubscribe();
        },
      };
    });
  }
}