-
-
Notifications
You must be signed in to change notification settings - Fork 454
/
offlineExchange.ts
178 lines (154 loc) · 4.55 KB
/
offlineExchange.ts
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { pipe, merge, makeSubject, share, filter } from 'wonka';
import { print, SelectionNode } from 'graphql';
import {
Operation,
Exchange,
ExchangeIO,
CombinedError,
createRequest,
makeOperation,
} from '@urql/core';
import {
getMainOperation,
getFragments,
isInlineFragment,
isFieldNode,
shouldInclude,
getSelectionSet,
getName,
} from './ast';
import {
SerializedRequest,
OptimisticMutationConfig,
Variables,
} from './types';
import { makeDict } from './helpers/dict';
import { cacheExchange, CacheExchangeOpts } from './cacheExchange';
import { toRequestPolicy } from './helpers/operation';
/** Determines whether a given query contains an optimistic mutation field */
const isOptimisticMutation = (
config: OptimisticMutationConfig,
operation: Operation
) => {
const vars: Variables = operation.variables || makeDict();
const fragments = getFragments(operation.query);
const selections = [...getSelectionSet(getMainOperation(operation.query))];
let field: void | SelectionNode;
while ((field = selections.pop())) {
if (!shouldInclude(field, vars)) {
continue;
} else if (!isFieldNode(field)) {
const fragmentNode = !isInlineFragment(field)
? fragments[getName(field)]
: field;
if (fragmentNode) selections.push(...getSelectionSet(fragmentNode));
} else if (config[getName(field)]) {
return true;
}
}
return false;
};
const isOfflineError = (error: undefined | CombinedError) =>
error &&
error.networkError &&
!error.response &&
((typeof navigator !== 'undefined' && navigator.onLine === false) ||
/request failed|failed to fetch|network\s?error/i.test(
error.networkError.message
));
export const offlineExchange = (opts: CacheExchangeOpts): Exchange => input => {
const { storage } = opts;
if (
storage &&
storage.onOnline &&
storage.readMetadata &&
storage.writeMetadata
) {
const { forward: outerForward, client, dispatchDebug } = input;
const { source: reboundOps$, next } = makeSubject<Operation>();
const optimisticMutations = opts.optimistic || {};
const failedQueue: Operation[] = [];
const updateMetadata = () => {
const requests: SerializedRequest[] = [];
for (let i = 0; i < failedQueue.length; i++) {
const operation = failedQueue[i];
if (operation.kind === 'mutation') {
requests.push({
query: print(operation.query),
variables: operation.variables,
});
}
}
storage.writeMetadata!(requests);
};
let isFlushingQueue = false;
const flushQueue = () => {
if (!isFlushingQueue) {
isFlushingQueue = true;
for (let i = 0; i < failedQueue.length; i++) {
const operation = failedQueue[i];
if (operation.kind === 'mutation') {
next(makeOperation('teardown', operation));
}
}
for (let i = 0; i < failedQueue.length; i++)
client.reexecuteOperation(failedQueue[i]);
failedQueue.length = 0;
isFlushingQueue = false;
updateMetadata();
}
};
const forward: ExchangeIO = ops$ => {
return pipe(
outerForward(ops$),
filter(res => {
if (
res.operation.kind === 'mutation' &&
isOfflineError(res.error) &&
isOptimisticMutation(optimisticMutations, res.operation)
) {
failedQueue.push(res.operation);
updateMetadata();
return false;
}
return true;
})
);
};
storage.onOnline(flushQueue);
storage.readMetadata().then(mutations => {
if (mutations) {
for (let i = 0; i < mutations.length; i++) {
failedQueue.push(
client.createRequestOperation(
'mutation',
createRequest(mutations[i].query, mutations[i].variables)
)
);
}
flushQueue();
}
});
const cacheResults$ = cacheExchange(opts)({
client,
dispatchDebug,
forward,
});
return ops$ => {
const sharedOps$ = share(ops$);
const opsAndRebound$ = merge([reboundOps$, sharedOps$]);
return pipe(
cacheResults$(opsAndRebound$),
filter(res => {
if (res.operation.kind === 'query' && isOfflineError(res.error)) {
next(toRequestPolicy(res.operation, 'cache-only'));
failedQueue.push(res.operation);
return false;
}
return true;
})
);
};
}
return cacheExchange(opts)(input);
};