summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/apollo/persist_link.js
blob: 9d95409d96c61773864e5d216a76145293faca33 (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// this file is based on https://github.com/apollographql/apollo-cache-persist/blob/master/examples/react-native/src/utils/persistence/persistLink.ts
// with some heavy refactororing

/* eslint-disable consistent-return */
/* eslint-disable @gitlab/require-i18n-strings */
/* eslint-disable no-param-reassign */
import { visit } from 'graphql';
import { ApolloLink } from '@apollo/client/core';
import traverse from 'traverse';

const extractPersistDirectivePaths = (originalQuery, directive = 'persist') => {
  const paths = [];
  const fragmentPaths = {};
  const fragmentPersistPaths = {};

  const query = visit(originalQuery, {
    FragmentSpread: ({ name: { value: name } }, _key, _parent, _path, ancestors) => {
      const root = ancestors.find(
        ({ kind }) => kind === 'OperationDefinition' || kind === 'FragmentDefinition',
      );

      const rootKey = root.kind === 'FragmentDefinition' ? root.name.value : '$ROOT';

      const fieldPath = ancestors
        .filter(({ kind }) => kind === 'Field')
        .map(({ name: { value } }) => value);

      fragmentPaths[name] = [rootKey].concat(fieldPath);
    },
    Directive: ({ name: { value: name } }, _key, _parent, _path, ancestors) => {
      if (name === directive) {
        const fieldPath = ancestors
          .filter(({ kind }) => kind === 'Field')
          .map(({ name: { value } }) => value);

        const fragmentDefinition = ancestors.find(({ kind }) => kind === 'FragmentDefinition');

        // If we are inside a fragment, we must save the reference.
        if (fragmentDefinition) {
          fragmentPersistPaths[fragmentDefinition.name.value] = fieldPath;
        } else if (fieldPath.length) {
          paths.push(fieldPath);
        }
        return null;
      }
    },
  });

  // In case there are any FragmentDefinition items, we need to combine paths.
  if (Object.keys(fragmentPersistPaths).length) {
    visit(originalQuery, {
      FragmentSpread: ({ name: { value: name } }, _key, _parent, _path, ancestors) => {
        if (fragmentPersistPaths[name]) {
          let fieldPath = ancestors
            .filter(({ kind }) => kind === 'Field')
            .map(({ name: { value } }) => value);

          fieldPath = fieldPath.concat(fragmentPersistPaths[name]);

          const fragment = name;
          let parent = fragmentPaths[fragment][0];

          while (parent && parent !== '$ROOT' && fragmentPaths[parent]) {
            fieldPath = fragmentPaths[parent].slice(1).concat(fieldPath);
            // eslint-disable-next-line prefer-destructuring
            parent = fragmentPaths[parent][0];
          }

          paths.push(fieldPath);
        }
      },
    });
  }

  return { query, paths };
};

/**
 * Given a data result object path, return the equivalent query selection path.
 *
 * @param {Array} path The data result object path. i.e.: ["a", 0, "b"]
 * @return {String} the query selection path. i.e.: "a.b"
 */
const toQueryPath = (path) => path.filter((key) => Number.isNaN(Number(key))).join('.');

const attachPersists = (paths, object) => {
  const queryPaths = paths.map(toQueryPath);
  function mapperFunction() {
    if (
      !this.isRoot &&
      this.node &&
      typeof this.node === 'object' &&
      Object.keys(this.node).length &&
      !Array.isArray(this.node)
    ) {
      const path = toQueryPath(this.path);

      this.update({
        __persist: Boolean(
          queryPaths.find(
            (queryPath) => queryPath.indexOf(path) === 0 || path.indexOf(queryPath) === 0,
          ),
        ),
        ...this.node,
      });
    }
  }

  return traverse(object).map(mapperFunction);
};

export const getPersistLink = () => {
  return new ApolloLink((operation, forward) => {
    const { query, paths } = extractPersistDirectivePaths(operation.query);

    // Noop if not a persist query
    if (!paths.length) {
      return forward(operation);
    }

    // Replace query with one without @persist directives.
    operation.query = query;

    // Remove requesting __persist fields.
    operation.query = visit(operation.query, {
      Field: ({ name: { value: name } }) => {
        if (name === '__persist') {
          return null;
        }
      },
    });

    return forward(operation).map((result) => {
      if (result.data) {
        result.data = attachPersists(paths, result.data);
      }

      return result;
    });
  });
};