-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
preloadQuery_DEPRECATED.js
281 lines (267 loc) · 8.34 KB
/
preloadQuery_DEPRECATED.js
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const {
createOperationDescriptor,
getRequest,
getRequestIdentifier,
Observable,
PreloadableQueryRegistry,
RelayFeatureFlags,
ReplaySubject,
} = require('relay-runtime');
import type {
PreloadableConcreteRequest,
PreloadedQueryInner_DEPRECATED,
PreloadFetchPolicy,
PreloadOptions,
PreloadQueryStatus,
VariablesOf,
} from './EntryPointTypes.flow';
import type {
ConcreteRequest,
GraphQLResponse,
GraphQLTaggedNode,
IEnvironment,
OperationType,
Subscription,
} from 'relay-runtime';
// Expire results by this delay after they resolve.
const DEFAULT_PREFETCH_TIMEOUT = 30 * 1000; // 30 seconds
const WEAKMAP_SUPPORTED = typeof WeakMap === 'function';
const STORE_OR_NETWORK_DEFAULT: PreloadFetchPolicy = 'store-or-network';
const pendingQueriesByEnvironment = WEAKMAP_SUPPORTED
? new WeakMap()
: new Map();
type PendingQueryEntry =
| $ReadOnly<{|
cacheKey: string,
fetchKey: ?string | ?number,
fetchPolicy: PreloadFetchPolicy,
kind: 'network',
id: ?string,
name: string,
status: PreloadQueryStatus,
subject: ReplaySubject<GraphQLResponse>,
subscription: Subscription,
|}>
| $ReadOnly<{|
cacheKey: string,
fetchKey: ?string | ?number,
fetchPolicy: PreloadFetchPolicy,
kind: 'cache',
id: ?string,
name: string,
status: PreloadQueryStatus,
|}>;
function preloadQuery<TQuery: OperationType, TEnvironmentProviderOptions>(
environment: IEnvironment,
preloadableRequest: GraphQLTaggedNode | PreloadableConcreteRequest<TQuery>,
variables: VariablesOf<TQuery>,
options?: ?PreloadOptions,
environmentProviderOptions?: ?TEnvironmentProviderOptions,
): PreloadedQueryInner_DEPRECATED<TQuery, TEnvironmentProviderOptions> {
let _pendingQueries = pendingQueriesByEnvironment.get(environment);
if (_pendingQueries == null) {
_pendingQueries = new Map();
pendingQueriesByEnvironment.set(environment, _pendingQueries);
}
const pendingQueries: Map<string, PendingQueryEntry> = _pendingQueries; // store in a const for flow
const queryEntry = preloadQueryDeduped(
environment,
pendingQueries,
preloadableRequest,
variables,
options,
);
const source =
queryEntry.kind === 'network'
? Observable.create(sink => {
let subscription;
if (pendingQueries.get(queryEntry.cacheKey) == null) {
const newQueryEntry = preloadQueryDeduped(
environment,
pendingQueries,
preloadableRequest,
variables,
options,
);
if (newQueryEntry.kind === 'network') {
subscription = newQueryEntry.subject.subscribe(sink);
}
} else {
subscription = queryEntry.subject.subscribe(sink);
}
return () => {
subscription?.unsubscribe();
if (environment.isServer()) {
return;
}
if (
RelayFeatureFlags.DELAY_CLEANUP_OF_PENDING_PRELOAD_QUERIES ===
true
) {
setTimeout(() => {
// Clear the cache entry after the default timeout
// null-check for Flow
if (queryEntry != null) {
cleanup(pendingQueries, queryEntry);
}
}, DEFAULT_PREFETCH_TIMEOUT);
} else {
cleanup(pendingQueries, queryEntry);
}
};
})
: null;
return {
kind: 'PreloadedQuery_DEPRECATED',
environment,
environmentProviderOptions,
fetchKey: queryEntry.fetchKey,
fetchPolicy: queryEntry.fetchPolicy,
networkCacheConfig: options?.networkCacheConfig,
id: queryEntry.id,
name: queryEntry.name,
source,
variables,
status: queryEntry.status,
};
}
function preloadQueryDeduped<TQuery: OperationType>(
environment: IEnvironment,
pendingQueries: Map<string, PendingQueryEntry>,
preloadableRequest: GraphQLTaggedNode | PreloadableConcreteRequest<TQuery>,
variables: VariablesOf<TQuery>,
options: ?PreloadOptions,
): PendingQueryEntry {
let params;
let query: ?ConcreteRequest;
if (preloadableRequest.kind === 'PreloadableConcreteRequest') {
const preloadableConcreteRequest: PreloadableConcreteRequest<TQuery> = (preloadableRequest: $FlowFixMe);
params = preloadableConcreteRequest.params;
query = params.id != null ? PreloadableQueryRegistry.get(params.id) : null;
} else {
query = getRequest((preloadableRequest: $FlowFixMe));
params = query.params;
}
const network = environment.getNetwork();
const fetchPolicy = options?.fetchPolicy ?? STORE_OR_NETWORK_DEFAULT;
const fetchKey = options?.fetchKey;
const networkCacheConfig = {
force: true,
...options?.networkCacheConfig,
};
const cacheKey = `${getRequestIdentifier(params, variables)}${
fetchKey != null ? `-${fetchKey}` : ''
}`;
const prevQueryEntry = pendingQueries.get(cacheKey);
const availability =
fetchPolicy === STORE_OR_NETWORK_DEFAULT && query != null && query != null
? environment.check(
createOperationDescriptor(query, variables, networkCacheConfig),
)
: {status: 'missing'};
let nextQueryEntry: ?PendingQueryEntry;
if (availability.status === 'available' && query != null) {
nextQueryEntry =
prevQueryEntry && prevQueryEntry.kind === 'cache'
? prevQueryEntry
: {
cacheKey,
fetchKey,
fetchPolicy,
kind: 'cache',
id: params.id,
name: params.name,
status: {
cacheConfig: networkCacheConfig,
source: 'cache',
fetchTime: availability?.fetchTime ?? null,
},
};
if (!environment.isServer() && prevQueryEntry == null) {
setTimeout(() => {
// Clear the cache entry after the default timeout
// null-check for Flow
if (nextQueryEntry != null) {
cleanup(pendingQueries, nextQueryEntry);
}
}, DEFAULT_PREFETCH_TIMEOUT);
}
} else if (prevQueryEntry == null || prevQueryEntry.kind !== 'network') {
// Should fetch but we're not already fetching: fetch!
const source = network.execute(params, variables, networkCacheConfig, null);
const subject = new ReplaySubject();
nextQueryEntry = {
cacheKey,
fetchKey,
fetchPolicy,
kind: 'network',
id: params.id,
name: params.name,
status: {
cacheConfig: networkCacheConfig,
source: 'network',
fetchTime: null,
},
subject,
subscription: source
.finally(() => {
if (environment.isServer()) {
return;
}
setTimeout(() => {
// Clear the cache entry after the default timeout
// null-check for Flow
if (nextQueryEntry != null) {
cleanup(pendingQueries, nextQueryEntry);
}
}, DEFAULT_PREFETCH_TIMEOUT);
})
.subscribe({
complete: () => {
subject.complete();
},
error: error => {
subject.error(error);
},
next: response => {
subject.next(response);
},
}),
};
} else {
nextQueryEntry = prevQueryEntry;
}
// $FlowFixMe[incompatible-call]
pendingQueries.set(cacheKey, nextQueryEntry);
// $FlowFixMe[incompatible-return]
return nextQueryEntry;
}
function cleanup(
pendingQueries: Map<string, PendingQueryEntry>,
entry: PendingQueryEntry,
): void {
// Reload the entry by its cache key and only invalidate if its the identical
// entry instance. This ensures that if the same query/variables are fetched
// successively that a timeout/expiration from an earlier fetch doesn't clear
// a subsequent fetch.
const currentEntry = pendingQueries.get(entry.cacheKey);
if (currentEntry != null && currentEntry === entry) {
if (currentEntry.kind === 'network') {
currentEntry.subscription.unsubscribe();
}
pendingQueries.delete(currentEntry.cacheKey);
}
}
module.exports = preloadQuery;