-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
GraphQLQueryRunner.js
297 lines (266 loc) · 8.61 KB
/
GraphQLQueryRunner.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule GraphQLQueryRunner
* @typechecks
* @flow
*/
'use strict';
var DliteFetchModeConstants = require('DliteFetchModeConstants');
import type {RelayQuerySet} from 'RelayInternalTypes';
import type {PendingFetch} from 'RelayPendingQueryTracker';
var RelayNetworkLayer = require('RelayNetworkLayer');
var RelayPendingQueryTracker = require('RelayPendingQueryTracker');
var RelayProfiler = require('RelayProfiler');
import type RelayQuery from 'RelayQuery';
var RelayStoreData = require('RelayStoreData');
var RelayTaskScheduler = require('RelayTaskScheduler');
var checkRelayQueryData = require('checkRelayQueryData');
var diffRelayQuery = require('diffRelayQuery');
var everyObject = require('everyObject');
var flattenSplitRelayQueries = require('flattenSplitRelayQueries');
var forEachObject = require('forEachObject');
var generateForceIndex = require('generateForceIndex');
var invariant = require('invariant');
var resolveImmediate = require('resolveImmediate');
var someObject = require('someObject');
var splitDeferredRelayQueries = require('splitDeferredRelayQueries');
var warning = require('warning');
import type {
Abortable,
ReadyStateChangeCallback
} from 'RelayTypes';
type PartialReadyState = {
aborted?: boolean;
done?: boolean;
error?: Error;
ready?: boolean;
stale?: boolean;
};
// The source of truth for application data.
var storeData = RelayStoreData.getDefaultInstance();
/**
* This is the high-level entry point for sending queries to the GraphQL
* endpoint. It provides methods for scheduling queries (`run`), force-fetching
* queries (ie. ignoring the cache; `forceFetch`).
*
* In order to send minimal queries and avoid re-retrieving data,
* `GraphQLQueryRunner` maintains a registry of pending (in-flight) queries, and
* "subtracts" those from any new queries that callers enqueue.
*
* @internal
*/
var GraphQLQueryRunner = {
/**
* Fetches data required to resolve a set of queries. See the `RelayStore`
* module for documentation on the callback.
*
* Fetch mode must be a value in `DliteFetchModeConstants`.
*/
run: function(
querySet: RelayQuerySet,
callback: ReadyStateChangeCallback,
fetchMode?: string
): Abortable {
var profiler = RelayProfiler.profile('RelayStore.primeCache', querySet);
fetchMode = fetchMode || DliteFetchModeConstants.FETCH_MODE_CLIENT;
var diffQueries = [];
if (fetchMode === DliteFetchModeConstants.FETCH_MODE_CLIENT) {
forEachObject(querySet, query => {
if (query) {
diffQueries.push(...diffRelayQuery(
query,
storeData.getRecordStore(),
storeData.getQueryTracker()
));
}
});
} else {
forEachObject(querySet, query => {
if (query) {
diffQueries.push(query);
}
});
}
return runQueries(diffQueries, callback, fetchMode, profiler);
},
/**
* Ignores the cache and fetches data required to resolve a set of queries.
* Uses the data we get back from the server to overwrite data in the cache.
*
* Even though we're ignoring the cache, we will still invoke the callback
* immediately with `ready: true` if `querySet` can be resolved by the cache.
*/
forceFetch: function(
querySet: RelayQuerySet,
callback: ReadyStateChangeCallback
): Abortable {
var profiler = RelayProfiler.profile('RelayStore.forceFetch', querySet);
var queries = [];
forEachObject(querySet, query => {
query && queries.push(query);
});
var fetchMode = DliteFetchModeConstants.FETCH_MODE_REFETCH;
return runQueries(queries, callback, fetchMode, profiler);
},
};
function canResolve(fetch: PendingFetch): boolean {
return checkRelayQueryData(
storeData.getQueuedStore(),
fetch.getQuery()
);
}
function hasItems(map: Object): boolean {
return !!Object.keys(map).length;
}
function splitAndFlattenQueries(
queries: Array<RelayQuery.Root>
): Array<RelayQuery.Root> {
if (!RelayNetworkLayer.supports('defer')) {
var hasDeferredDescendant = queries.some(query => {
if (query.hasDeferredDescendant()) {
warning(
false,
'Relay: Query `%s` contains a deferred fragment (e.g. ' +
'`getFragment(\'foo\').defer()`) which is not supported by the ' +
'default network layer. This query will be sent without deferral.',
query.getName()
);
return true;
}
});
if (hasDeferredDescendant) {
return queries;
}
}
var flattenedQueries = [];
queries.forEach(query => {
return flattenedQueries.push(
...flattenSplitRelayQueries(
splitDeferredRelayQueries(query)
)
);
});
return flattenedQueries;
}
function runQueries(
queries: Array<RelayQuery.Root>,
callback: ReadyStateChangeCallback,
fetchMode: string,
profiler: {stop: () => void}
): Abortable {
var readyState = {
aborted: false,
done: false,
error: null,
ready: false,
stale: false,
};
var scheduled = false;
function setReadyState(partial: PartialReadyState): void {
if (readyState.aborted) {
return;
}
if (readyState.done || readyState.error) {
invariant(
partial.aborted,
'GraphQLQueryRunner: Unexpected ready state change.'
);
return;
}
readyState = {
aborted: partial.aborted != null ? partial.aborted : readyState.aborted,
done: partial.done != null ? partial.done : readyState.done,
error: partial.error != null ? partial.error : readyState.error,
ready: partial.ready != null ? partial.ready : readyState.ready,
stale: partial.stale != null ? partial.stale : readyState.stale,
};
if (scheduled) {
return;
}
scheduled = true;
resolveImmediate(() => {
scheduled = false;
callback(readyState);
});
}
var remainingFetchMap: {[queryID: string]: PendingFetch} = {};
var remainingRequiredFetchMap: {[queryID: string]: PendingFetch} = {};
function onResolved(pendingFetch: PendingFetch) {
var pendingQuery = pendingFetch.getQuery();
var pendingQueryID = pendingQuery.getID();
delete remainingFetchMap[pendingQueryID];
if (!pendingQuery.isDeferred()) {
delete remainingRequiredFetchMap[pendingQueryID];
}
if (hasItems(remainingRequiredFetchMap)) {
return;
}
if (someObject(remainingFetchMap, query => query.isResolvable())) {
// The other resolvable query will resolve imminently and call
// `setReadyState` instead.
return;
}
if (hasItems(remainingFetchMap)) {
setReadyState({done: false, ready: true, stale: false});
} else {
setReadyState({done: true, ready: true, stale: false});
}
}
function onRejected(pendingFetch: PendingFetch, error: Error) {
setReadyState({error});
var pendingQuery = pendingFetch.getQuery();
var pendingQueryID = pendingQuery.getID();
delete remainingFetchMap[pendingQueryID];
if (!pendingQuery.isDeferred()) {
delete remainingRequiredFetchMap[pendingQueryID];
}
}
RelayTaskScheduler.await(() => {
var forceIndex = fetchMode === DliteFetchModeConstants.FETCH_MODE_REFETCH ?
generateForceIndex() : null;
splitAndFlattenQueries(queries).forEach(query => {
var pendingFetch = RelayPendingQueryTracker.add(
{query, fetchMode, forceIndex, storeData}
);
var queryID = query.getID();
remainingFetchMap[queryID] = pendingFetch;
if (!query.isDeferred()) {
remainingRequiredFetchMap[queryID] = pendingFetch;
}
pendingFetch.getResolvedPromise().then(
onResolved.bind(null, pendingFetch),
onRejected.bind(null, pendingFetch)
);
});
if (!hasItems(remainingFetchMap)) {
setReadyState({done: true, ready: true});
} else {
if (!hasItems(remainingRequiredFetchMap)) {
setReadyState({ready: true});
} else {
setReadyState({ready: false});
storeData.runWithDiskCache(() => {
if (hasItems(remainingRequiredFetchMap)) {
if (everyObject(remainingRequiredFetchMap, canResolve)) {
setReadyState({ready: true, stale: true});
}
}
});
}
}
}).done();
// Stop profiling when synchronous work has completed.
profiler.stop();
return {
abort(): void {
setReadyState({aborted: true});
}
};
}
module.exports = GraphQLQueryRunner;