-
-
Notifications
You must be signed in to change notification settings - Fork 462
/
Copy pathofflineExchange.ts
243 lines (218 loc) · 7.02 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { pipe, share, merge, makeSubject, filter } from 'wonka';
import { SelectionNode } from '@0no-co/graphql.web';
import {
Operation,
OperationResult,
Exchange,
ExchangeIO,
CombinedError,
stringifyDocument,
createRequest,
makeOperation,
} from '@urql/core';
import {
getMainOperation,
getFragments,
isInlineFragment,
isFieldNode,
shouldInclude,
getSelectionSet,
getName,
} from './ast';
import {
SerializedRequest,
OptimisticMutationConfig,
Variables,
CacheExchangeOpts,
StorageAdapter,
} from './types';
import { cacheExchange } from './cacheExchange';
import { toRequestPolicy } from './helpers/operation';
/** Determines whether a given query contains an optimistic mutation field */
const isOptimisticMutation = <T extends OptimisticMutationConfig>(
config: T,
operation: Operation
) => {
const vars: Variables = operation.variables || {};
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;
};
/** Input parameters for the {@link offlineExchange}.
* @remarks
* This configuration object extends the {@link CacheExchangeOpts}
* as the `offlineExchange` extends the regular {@link cacheExchange}.
*/
export interface OfflineExchangeOpts extends CacheExchangeOpts {
/** Configures an offline storage adapter for Graphcache.
*
* @remarks
* A {@link StorageAdapter} allows Graphcache to write data to an external,
* asynchronous storage, and hydrate data from it when it first loads.
* This allows you to preserve normalized data between restarts/reloads.
*
* @see {@link https://urql.dev/goto/docs/graphcache/offline} for the full Offline Support docs.
*/
storage: StorageAdapter;
/** Predicate function to determine whether a {@link CombinedError} hints at a network error.
*
* @remarks
* Not ever {@link CombinedError} means that the device is offline and by default
* the `offlineExchange` will check for common network error messages and check
* `navigator.onLine`. However, when `isOfflineError` is passed it can replace
* the default offline detection.
*/
isOfflineError?(
error: undefined | CombinedError,
result: OperationResult
): boolean;
}
/** Exchange factory that creates a normalized cache exchange in Offline Support mode.
*
* @param opts - A {@link OfflineExchangeOpts} configuration object.
* @returns the created normalized, offline cache {@link Exchange}.
*
* @remarks
* The `offlineExchange` is a wrapper around the regular {@link cacheExchange}
* which adds logic via the {@link OfflineExchangeOpts.storage} adapter to
* recognize when it’s offline, when to retry failed mutations, and how
* to handle longer periods of being offline.
*
* @see {@link https://urql.dev/goto/docs/graphcache/offline} for the full Offline Support docs.
*/
export const offlineExchange =
<C extends OfflineExchangeOpts>(opts: C): Exchange =>
input => {
const { storage } = opts;
const isOfflineError =
opts.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
)));
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: stringifyDocument(operation.query),
variables: operation.variables,
extensions: operation.extensions,
});
}
}
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, res) &&
isOptimisticMutation(optimisticMutations, res.operation)
) {
failedQueue.push(res.operation);
updateMetadata();
return false;
}
return true;
}),
share
);
};
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),
mutations[i].extensions
)
);
}
flushQueue();
}
})
.finally(() => storage.onOnline!(flushQueue));
const cacheResults$ = cacheExchange({
...opts,
storage: {
...storage,
readData() {
return storage.readData().finally(flushQueue);
},
},
})({
client,
dispatchDebug,
forward,
});
return operations$ => {
const opsAndRebound$ = merge([reboundOps$, operations$]);
return pipe(
cacheResults$(opsAndRebound$),
filter(res => {
if (
res.operation.kind === 'query' &&
isOfflineError(res.error, res)
) {
next(toRequestPolicy(res.operation, 'cache-only'));
failedQueue.push(res.operation);
return false;
}
return true;
})
);
};
}
return cacheExchange(opts)(input);
};