relay-runtime 8.0.0 → 10.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/handlers/RelayDefaultHandlerProvider.js.flow +41 -0
  2. package/handlers/connection/ConnectionHandler.js.flow +549 -0
  3. package/handlers/connection/ConnectionInterface.js.flow +92 -0
  4. package/handlers/connection/MutationHandlers.js.flow +88 -0
  5. package/index.js +1 -1
  6. package/index.js.flow +320 -0
  7. package/lib/handlers/RelayDefaultHandlerProvider.js +13 -2
  8. package/lib/handlers/connection/{RelayConnectionHandler.js → ConnectionHandler.js} +33 -35
  9. package/lib/handlers/connection/{RelayConnectionInterface.js → ConnectionInterface.js} +2 -2
  10. package/lib/handlers/connection/MutationHandlers.js +86 -0
  11. package/lib/index.js +15 -19
  12. package/lib/mutations/RelayDeclarativeMutationConfig.js +29 -52
  13. package/lib/mutations/RelayRecordProxy.js +1 -3
  14. package/lib/mutations/RelayRecordSourceMutator.js +2 -9
  15. package/lib/mutations/RelayRecordSourceProxy.js +2 -4
  16. package/lib/mutations/RelayRecordSourceSelectorProxy.js +1 -13
  17. package/lib/mutations/commitMutation.js +13 -3
  18. package/lib/mutations/validateMutation.js +16 -9
  19. package/lib/network/RelayObservable.js +9 -9
  20. package/lib/network/RelayQueryResponseCache.js +8 -6
  21. package/lib/query/PreloadableQueryRegistry.js +70 -0
  22. package/lib/query/fetchQueryInternal.js +31 -23
  23. package/lib/store/DataChecker.js +122 -110
  24. package/lib/store/RelayConcreteVariables.js +6 -2
  25. package/lib/store/RelayModernEnvironment.js +121 -67
  26. package/lib/store/RelayModernFragmentSpecResolver.js +12 -16
  27. package/lib/store/RelayModernQueryExecutor.js +389 -314
  28. package/lib/store/RelayModernRecord.js +14 -9
  29. package/lib/store/RelayModernSelector.js +7 -3
  30. package/lib/store/RelayModernStore.js +289 -484
  31. package/lib/store/RelayOperationTracker.js +35 -78
  32. package/lib/store/RelayOptimisticRecordSource.js +7 -5
  33. package/lib/store/RelayPublishQueue.js +6 -33
  34. package/lib/store/RelayReader.js +113 -45
  35. package/lib/store/RelayRecordSource.js +2 -9
  36. package/lib/store/RelayRecordSourceMapImpl.js +13 -18
  37. package/lib/store/RelayReferenceMarker.js +40 -60
  38. package/lib/store/RelayResponseNormalizer.js +158 -193
  39. package/lib/store/RelayStoreUtils.js +1 -0
  40. package/lib/store/StoreInspector.js +8 -8
  41. package/lib/store/TypeID.js +28 -0
  42. package/lib/store/cloneRelayScalarHandleSourceField.js +44 -0
  43. package/lib/store/normalizeRelayPayload.js +6 -2
  44. package/lib/store/readInlineData.js +1 -1
  45. package/lib/subscription/requestSubscription.js +5 -3
  46. package/lib/util/RelayConcreteNode.js +9 -6
  47. package/lib/util/RelayError.js +39 -9
  48. package/lib/util/RelayFeatureFlags.js +2 -5
  49. package/lib/util/RelayReplaySubject.js +3 -3
  50. package/lib/util/createPayloadFor3DField.js +7 -2
  51. package/lib/util/getRequestIdentifier.js +2 -2
  52. package/lib/util/recycleNodesInto.js +2 -6
  53. package/mutations/RelayDeclarativeMutationConfig.js.flow +380 -0
  54. package/mutations/RelayRecordProxy.js.flow +165 -0
  55. package/mutations/RelayRecordSourceMutator.js.flow +238 -0
  56. package/mutations/RelayRecordSourceProxy.js.flow +164 -0
  57. package/mutations/RelayRecordSourceSelectorProxy.js.flow +119 -0
  58. package/mutations/applyOptimisticMutation.js.flow +76 -0
  59. package/mutations/commitLocalUpdate.js.flow +24 -0
  60. package/mutations/commitMutation.js.flow +182 -0
  61. package/mutations/validateMutation.js.flow +213 -0
  62. package/network/ConvertToExecuteFunction.js.flow +49 -0
  63. package/network/RelayNetwork.js.flow +84 -0
  64. package/network/RelayNetworkTypes.js.flow +123 -0
  65. package/network/RelayObservable.js.flow +634 -0
  66. package/network/RelayQueryResponseCache.js.flow +111 -0
  67. package/package.json +1 -1
  68. package/query/GraphQLTag.js.flow +166 -0
  69. package/query/PreloadableQueryRegistry.js.flow +65 -0
  70. package/query/fetchQuery.js.flow +47 -0
  71. package/query/fetchQueryInternal.js.flow +348 -0
  72. package/relay-runtime.js +2 -2
  73. package/relay-runtime.min.js +2 -2
  74. package/store/ClientID.js.flow +43 -0
  75. package/store/DataChecker.js.flow +502 -0
  76. package/store/RelayConcreteVariables.js.flow +96 -0
  77. package/store/RelayModernEnvironment.js.flow +551 -0
  78. package/store/RelayModernFragmentSpecResolver.js.flow +426 -0
  79. package/store/RelayModernOperationDescriptor.js.flow +88 -0
  80. package/store/RelayModernQueryExecutor.js.flow +1321 -0
  81. package/store/RelayModernRecord.js.flow +403 -0
  82. package/store/RelayModernSelector.js.flow +455 -0
  83. package/store/RelayModernStore.js.flow +842 -0
  84. package/store/RelayOperationTracker.js.flow +164 -0
  85. package/store/RelayOptimisticRecordSource.js.flow +119 -0
  86. package/store/RelayPublishQueue.js.flow +401 -0
  87. package/store/RelayReader.js.flow +473 -0
  88. package/store/RelayRecordSource.js.flow +29 -0
  89. package/store/RelayRecordSourceMapImpl.js.flow +87 -0
  90. package/store/RelayRecordState.js.flow +37 -0
  91. package/store/RelayReferenceMarker.js.flow +257 -0
  92. package/store/RelayResponseNormalizer.js.flow +680 -0
  93. package/store/RelayStoreTypes.js.flow +899 -0
  94. package/store/RelayStoreUtils.js.flow +219 -0
  95. package/store/StoreInspector.js.flow +171 -0
  96. package/store/TypeID.js.flow +28 -0
  97. package/store/ViewerPattern.js.flow +26 -0
  98. package/store/cloneRelayHandleSourceField.js.flow +66 -0
  99. package/store/cloneRelayScalarHandleSourceField.js.flow +62 -0
  100. package/store/createFragmentSpecResolver.js.flow +55 -0
  101. package/store/createRelayContext.js.flow +44 -0
  102. package/store/defaultGetDataID.js.flow +27 -0
  103. package/store/hasOverlappingIDs.js.flow +34 -0
  104. package/store/isRelayModernEnvironment.js.flow +27 -0
  105. package/store/normalizeRelayPayload.js.flow +51 -0
  106. package/store/readInlineData.js.flow +75 -0
  107. package/subscription/requestSubscription.js.flow +100 -0
  108. package/util/JSResourceTypes.flow.js.flow +20 -0
  109. package/util/NormalizationNode.js.flow +198 -0
  110. package/util/ReaderNode.js.flow +208 -0
  111. package/util/RelayConcreteNode.js.flow +93 -0
  112. package/util/RelayDefaultHandleKey.js.flow +17 -0
  113. package/util/RelayError.js.flow +62 -0
  114. package/util/RelayFeatureFlags.js.flow +30 -0
  115. package/util/RelayProfiler.js.flow +284 -0
  116. package/util/RelayReplaySubject.js.flow +135 -0
  117. package/util/RelayRuntimeTypes.js.flow +72 -0
  118. package/util/createPayloadFor3DField.js.flow +43 -0
  119. package/util/deepFreeze.js.flow +36 -0
  120. package/util/generateID.js.flow +21 -0
  121. package/util/getFragmentIdentifier.js.flow +52 -0
  122. package/util/getRelayHandleKey.js.flow +41 -0
  123. package/util/getRequestIdentifier.js.flow +42 -0
  124. package/util/isPromise.js.flow +21 -0
  125. package/util/isScalarAndEqual.js.flow +26 -0
  126. package/util/recycleNodesInto.js.flow +76 -0
  127. package/util/resolveImmediate.js.flow +30 -0
  128. package/util/stableCopy.js.flow +35 -0
  129. package/lib/handlers/RelayDefaultMissingFieldHandlers.js +0 -26
  130. package/lib/handlers/getRelayDefaultMissingFieldHandlers.js +0 -36
  131. package/lib/query/RelayModernGraphQLTag.js +0 -104
  132. package/lib/store/RelayConnection.js +0 -37
  133. package/lib/store/RelayConnectionResolver.js +0 -178
  134. package/lib/store/RelayRecordSourceObjectImpl.js +0 -79
  135. package/lib/util/getFragmentSpecIdentifier.js +0 -27
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict-local
8
+ * @format
9
+ */
10
+
11
+ // flowlint ambiguous-object-type:error
12
+
13
+ 'use strict';
14
+
15
+ const Observable = require('../network/RelayObservable');
16
+ const RelayReplaySubject = require('../util/RelayReplaySubject');
17
+
18
+ const invariant = require('invariant');
19
+
20
+ import type {GraphQLResponse} from '../network/RelayNetworkTypes';
21
+ import type {Subscription} from '../network/RelayObservable';
22
+ import type {
23
+ IEnvironment,
24
+ OperationDescriptor,
25
+ RequestDescriptor,
26
+ } from '../store/RelayStoreTypes';
27
+ import type {CacheConfig} from '../util/RelayRuntimeTypes';
28
+ import type {RequestIdentifier} from '../util/getRequestIdentifier';
29
+
30
+ type RequestCacheEntry = {|
31
+ +identifier: RequestIdentifier,
32
+ +subject: RelayReplaySubject<GraphQLResponse>,
33
+ +subjectForInFlightStatus: RelayReplaySubject<GraphQLResponse>,
34
+ +subscription: Subscription,
35
+ |};
36
+
37
+ const WEAKMAP_SUPPORTED = typeof WeakMap === 'function';
38
+
39
+ const requestCachesByEnvironment = WEAKMAP_SUPPORTED
40
+ ? new WeakMap()
41
+ : new Map();
42
+
43
+ /**
44
+ * Fetches the given query and variables on the provided environment,
45
+ * and de-dupes identical in-flight requests.
46
+ *
47
+ * Observing a request:
48
+ * ====================
49
+ * fetchQuery returns an Observable which you can call .subscribe()
50
+ * on. subscribe() takes an Observer, which you can provide to
51
+ * observe network events:
52
+ *
53
+ * ```
54
+ * fetchQuery(environment, query, variables).subscribe({
55
+ * // Called when network requests starts
56
+ * start: (subscription) => {},
57
+ *
58
+ * // Called after a payload is received and written to the local store
59
+ * next: (payload) => {},
60
+ *
61
+ * // Called when network requests errors
62
+ * error: (error) => {},
63
+ *
64
+ * // Called when network requests fully completes
65
+ * complete: () => {},
66
+ *
67
+ * // Called when network request is unsubscribed
68
+ * unsubscribe: (subscription) => {},
69
+ * });
70
+ * ```
71
+ *
72
+ * In-flight request de-duping:
73
+ * ============================
74
+ * By default, calling fetchQuery multiple times with the same
75
+ * environment, query and variables will not initiate a new request if a request
76
+ * for those same parameters is already in flight.
77
+ *
78
+ * A request is marked in-flight from the moment it starts until the moment it
79
+ * fully completes, regardless of error or successful completion.
80
+ *
81
+ * NOTE: If the request completes _synchronously_, calling fetchQuery
82
+ * a second time with the same arguments in the same tick will _NOT_ de-dupe
83
+ * the request given that it will no longer be in-flight.
84
+ *
85
+ *
86
+ * Data Retention:
87
+ * ===============
88
+ * This function will not retain any query data outside the scope of the
89
+ * request, which means it is not guaranteed that it won't be garbage
90
+ * collected after the request completes.
91
+ * If you need to retain data, you can do so manually with environment.retain().
92
+ *
93
+ * Cancelling requests:
94
+ * ====================
95
+ * If the subscription returned by subscribe is called while the
96
+ * request is in-flight, apart from releasing retained data, the request will
97
+ * also be cancelled.
98
+ *
99
+ * ```
100
+ * const subscription = fetchQuery(...).subscribe(...);
101
+ *
102
+ * // This will cancel the request if it is in-flight.
103
+ * subscription.unsubscribe();
104
+ * ```
105
+ */
106
+ function fetchQuery(
107
+ environment: IEnvironment,
108
+ operation: OperationDescriptor,
109
+ options?: {|
110
+ networkCacheConfig?: CacheConfig,
111
+ |},
112
+ ): Observable<GraphQLResponse> {
113
+ return fetchQueryDeduped(environment, operation.request.identifier, () =>
114
+ environment.execute({
115
+ operation,
116
+ cacheConfig: options?.networkCacheConfig,
117
+ }),
118
+ );
119
+ }
120
+
121
+ /**
122
+ * Low-level implementation details of `fetchQuery`.
123
+ *
124
+ * `fetchQueryDeduped` can also be used to share a single cache for
125
+ * requests that aren't using `fetchQuery` directly (e.g. because they don't
126
+ * have an `OperationDescriptor` when they are called).
127
+ */
128
+ function fetchQueryDeduped(
129
+ environment: IEnvironment,
130
+ identifier: RequestIdentifier,
131
+ fetchFn: () => Observable<GraphQLResponse>,
132
+ ): Observable<GraphQLResponse> {
133
+ return Observable.create(sink => {
134
+ const requestCache = getRequestCache(environment);
135
+ let cachedRequest = requestCache.get(identifier);
136
+
137
+ if (!cachedRequest) {
138
+ fetchFn()
139
+ .finally(() => requestCache.delete(identifier))
140
+ .subscribe({
141
+ start: subscription => {
142
+ cachedRequest = {
143
+ identifier,
144
+ subject: new RelayReplaySubject(),
145
+ subjectForInFlightStatus: new RelayReplaySubject(),
146
+ subscription: subscription,
147
+ };
148
+ requestCache.set(identifier, cachedRequest);
149
+ },
150
+ next: response => {
151
+ const cachedReq = getCachedRequest(requestCache, identifier);
152
+ cachedReq.subject.next(response);
153
+ cachedReq.subjectForInFlightStatus.next(response);
154
+ },
155
+ error: error => {
156
+ const cachedReq = getCachedRequest(requestCache, identifier);
157
+ cachedReq.subject.error(error);
158
+ cachedReq.subjectForInFlightStatus.error(error);
159
+ },
160
+ complete: () => {
161
+ const cachedReq = getCachedRequest(requestCache, identifier);
162
+ cachedReq.subject.complete();
163
+ cachedReq.subjectForInFlightStatus.complete();
164
+ },
165
+ unsubscribe: subscription => {
166
+ const cachedReq = getCachedRequest(requestCache, identifier);
167
+ cachedReq.subject.unsubscribe();
168
+ cachedReq.subjectForInFlightStatus.unsubscribe();
169
+ },
170
+ });
171
+ }
172
+
173
+ invariant(
174
+ cachedRequest != null,
175
+ '[fetchQueryInternal] fetchQueryDeduped: Expected `start` to be ' +
176
+ 'called synchronously',
177
+ );
178
+ return getObservableForCachedRequest(requestCache, cachedRequest).subscribe(
179
+ sink,
180
+ );
181
+ });
182
+ }
183
+
184
+ /**
185
+ * @private
186
+ */
187
+ function getObservableForCachedRequest(
188
+ requestCache: Map<RequestIdentifier, RequestCacheEntry>,
189
+ cachedRequest: RequestCacheEntry,
190
+ ): Observable<GraphQLResponse> {
191
+ return Observable.create(sink => {
192
+ const subscription = cachedRequest.subject.subscribe(sink);
193
+
194
+ return () => {
195
+ subscription.unsubscribe();
196
+ const cachedRequestInstance = requestCache.get(cachedRequest.identifier);
197
+ if (cachedRequestInstance) {
198
+ const requestSubscription = cachedRequestInstance.subscription;
199
+ if (
200
+ requestSubscription != null &&
201
+ cachedRequestInstance.subject.getObserverCount() === 0
202
+ ) {
203
+ requestSubscription.unsubscribe();
204
+ requestCache.delete(cachedRequest.identifier);
205
+ }
206
+ }
207
+ };
208
+ });
209
+ }
210
+
211
+ /**
212
+ * @private
213
+ */
214
+ function getActiveStatusObservableForCachedRequest(
215
+ environment: IEnvironment,
216
+ requestCache: Map<RequestIdentifier, RequestCacheEntry>,
217
+ cachedRequest: RequestCacheEntry,
218
+ ): Observable<void> {
219
+ return Observable.create(sink => {
220
+ const subscription = cachedRequest.subjectForInFlightStatus.subscribe({
221
+ error: sink.error,
222
+ next: response => {
223
+ if (!environment.isRequestActive(cachedRequest.identifier)) {
224
+ sink.complete();
225
+ return;
226
+ }
227
+ sink.next();
228
+ },
229
+ complete: sink.complete,
230
+ unsubscribe: sink.complete,
231
+ });
232
+
233
+ return () => {
234
+ subscription.unsubscribe();
235
+ };
236
+ });
237
+ }
238
+
239
+ /**
240
+ * If a request is active for the given query, variables and environment,
241
+ * this function will return a Promise that will resolve when that request has
242
+ * stops being active (receives a final payload), and the data has been saved
243
+ * to the store.
244
+ * If no request is active, null will be returned
245
+ */
246
+ function getPromiseForActiveRequest(
247
+ environment: IEnvironment,
248
+ request: RequestDescriptor,
249
+ ): Promise<void> | null {
250
+ const requestCache = getRequestCache(environment);
251
+ const cachedRequest = requestCache.get(request.identifier);
252
+ if (!cachedRequest) {
253
+ return null;
254
+ }
255
+ if (!environment.isRequestActive(cachedRequest.identifier)) {
256
+ return null;
257
+ }
258
+
259
+ return new Promise((resolve, reject) => {
260
+ let resolveOnNext = false;
261
+ getActiveStatusObservableForCachedRequest(
262
+ environment,
263
+ requestCache,
264
+ cachedRequest,
265
+ ).subscribe({
266
+ complete: resolve,
267
+ error: reject,
268
+ next: response => {
269
+ /*
270
+ * The underlying `RelayReplaySubject` will synchronously replay events
271
+ * as soon as we subscribe, but since we want the *next* asynchronous
272
+ * one, we'll ignore them until the replay finishes.
273
+ */
274
+ if (resolveOnNext) {
275
+ resolve(response);
276
+ }
277
+ },
278
+ });
279
+ resolveOnNext = true;
280
+ });
281
+ }
282
+
283
+ /**
284
+ * If there is a pending request for the given query, returns an Observable of
285
+ * *all* its responses. Existing responses are published synchronously and
286
+ * subsequent responses are published asynchronously. Returns null if there is
287
+ * no pending request. This is similar to fetchQuery() except that it will not
288
+ * issue a fetch if there isn't already one pending.
289
+ */
290
+ function getObservableForActiveRequest(
291
+ environment: IEnvironment,
292
+ request: RequestDescriptor,
293
+ ): Observable<void> | null {
294
+ const requestCache = getRequestCache(environment);
295
+ const cachedRequest = requestCache.get(request.identifier);
296
+ if (!cachedRequest) {
297
+ return null;
298
+ }
299
+ if (!environment.isRequestActive(cachedRequest.identifier)) {
300
+ return null;
301
+ }
302
+
303
+ return getActiveStatusObservableForCachedRequest(
304
+ environment,
305
+ requestCache,
306
+ cachedRequest,
307
+ );
308
+ }
309
+
310
+ /**
311
+ * @private
312
+ */
313
+ function getRequestCache(
314
+ environment: IEnvironment,
315
+ ): Map<RequestIdentifier, RequestCacheEntry> {
316
+ const cached: ?Map<
317
+ RequestIdentifier,
318
+ RequestCacheEntry,
319
+ > = requestCachesByEnvironment.get(environment);
320
+ if (cached != null) {
321
+ return cached;
322
+ }
323
+ const requestCache: Map<RequestIdentifier, RequestCacheEntry> = new Map();
324
+ requestCachesByEnvironment.set(environment, requestCache);
325
+ return requestCache;
326
+ }
327
+
328
+ /**
329
+ * @private
330
+ */
331
+ function getCachedRequest(
332
+ requestCache: Map<RequestIdentifier, RequestCacheEntry>,
333
+ identifier: RequestIdentifier,
334
+ ) {
335
+ const cached = requestCache.get(identifier);
336
+ invariant(
337
+ cached != null,
338
+ '[fetchQueryInternal] getCachedRequest: Expected request to be cached',
339
+ );
340
+ return cached;
341
+ }
342
+
343
+ module.exports = {
344
+ fetchQuery,
345
+ fetchQueryDeduped,
346
+ getPromiseForActiveRequest,
347
+ getObservableForActiveRequest,
348
+ };