@jsb188/graphql 1.1.8 → 1.1.11
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.
- package/cache/config.ts +66 -42
- package/cache/index.test.ts +881 -0
- package/cache/index.ts +1815 -979
- package/cache/persist.ts +721 -0
- package/cache/store.ts +437 -0
- package/client/data-table-realtime-subscriptions.test.ts +740 -0
- package/client/data-table-realtime-subscriptions.ts +955 -0
- package/client/data-table-realtime.test.ts +792 -0
- package/client/data-table-realtime.ts +1218 -0
- package/client/fragment-realtime-sequence.ts +52 -0
- package/client/index.ts +4 -2
- package/client/open-sheet.ts +137 -0
- package/client/request-managed-session.test.ts +574 -0
- package/client/request-no-store.test.ts +157 -0
- package/client/request.ts +973 -143
- package/client/sse-ticket.test.ts +26 -0
- package/deno.lock +170 -0
- package/deno.test.json +10 -0
- package/drafts/index.ts +149 -0
- package/drafts/store.ts +397 -0
- package/gql/eagerQueryMap.ts +12 -0
- package/gql/fragments/accountAuthFragments.ts +5 -0
- package/gql/fragments/accountFragments.ts +1 -3
- package/gql/fragments/accountSessionFragments.ts +16 -0
- package/gql/fragments/agentDocFragments.ts +46 -0
- package/gql/fragments/agentMemoryFragments.ts +19 -0
- package/gql/fragments/aiChatFragments.ts +17 -0
- package/gql/fragments/billingFragments.ts +0 -11
- package/gql/fragments/campaignFragments.ts +277 -0
- package/gql/fragments/dataTableFragments.ts +102 -0
- package/gql/fragments/emailFragments.ts +36 -0
- package/gql/fragments/fieldDocFragments.ts +82 -0
- package/gql/fragments/inboundContactFragments.ts +15 -0
- package/gql/fragments/integrationFragments.ts +22 -0
- package/gql/fragments/logFragments.ts +33 -64
- package/gql/fragments/organizationFragments.ts +94 -21
- package/gql/fragments/scheduleFragments.ts +155 -0
- package/gql/fragments/sheetFragments.ts +675 -0
- package/gql/fragments/storageFragments.ts +21 -1
- package/gql/fragments/workflowFragments.ts +67 -0
- package/gql/mutations/accountMutations.ts +24 -4
- package/gql/mutations/agentDocMutations.ts +177 -0
- package/gql/mutations/agentMemoryMutations.ts +36 -0
- package/gql/mutations/aiChatMutations.ts +43 -3
- package/gql/mutations/authMutations.ts +160 -19
- package/gql/mutations/campaignMutations.ts +215 -0
- package/gql/mutations/dataTableMutations.ts +106 -0
- package/gql/mutations/fieldDocMutations.ts +24 -0
- package/gql/mutations/inboundContactMutations.ts +24 -0
- package/gql/mutations/index.ts +17 -8
- package/gql/mutations/integrationMutations.ts +25 -0
- package/gql/mutations/logMutations.ts +10 -19
- package/gql/mutations/organizationMutations.ts +160 -2
- package/gql/mutations/scheduleMutations.ts +423 -0
- package/gql/mutations/sheetMutations.ts +385 -0
- package/gql/mutations/storageMutations.ts +21 -2
- package/gql/mutations/workflowMutations.ts +42 -0
- package/gql/queries/agentDocQueries.ts +120 -0
- package/gql/queries/agentMemoryQueries.ts +22 -0
- package/gql/queries/aiChatQueries.ts +18 -2
- package/gql/queries/authQueries.ts +41 -0
- package/gql/queries/billingQueries.ts +24 -1
- package/gql/queries/campaignQueries.ts +127 -0
- package/gql/queries/dataTableQueries.ts +134 -0
- package/gql/queries/emailQueries.ts +96 -0
- package/gql/queries/fieldDocQueries.ts +158 -0
- package/gql/queries/inboundContactQueries.ts +40 -0
- package/gql/queries/index.ts +17 -6
- package/gql/queries/logQueries.ts +42 -32
- package/gql/queries/organizationQueries.ts +113 -8
- package/gql/queries/scheduleQueries.ts +315 -0
- package/gql/queries/sheetQueries.ts +383 -0
- package/gql/queries/storageQueries.ts +38 -0
- package/gql/queries/workflowQueries.ts +99 -0
- package/hooks/index.ts +2104 -860
- package/hooks/use-account-mtn.ts +91 -48
- package/hooks/use-agentDoc-mtn.ts +285 -0
- package/hooks/use-agentDoc-qry.ts +208 -0
- package/hooks/use-agentMemory-mtn.ts +73 -0
- package/hooks/use-agentMemory-qry.ts +44 -0
- package/hooks/use-aiChat-mtn.ts +248 -97
- package/hooks/use-aiChat-qry.ts +501 -191
- package/hooks/use-app-qry.ts +14 -11
- package/hooks/use-auth-mtn.ts +410 -256
- package/hooks/use-auth-qry.ts +51 -0
- package/hooks/use-campaign-mtn.ts +377 -0
- package/hooks/use-campaign-qry.ts +257 -0
- package/hooks/use-dataTable-mtn.ts +170 -0
- package/hooks/use-dataTable-qry.ts +996 -0
- package/hooks/use-email-qry.ts +227 -0
- package/hooks/use-fieldDoc-mtn.ts +50 -0
- package/hooks/use-fieldDoc-qry.ts +180 -0
- package/hooks/use-inboundContact-mtn.ts +34 -0
- package/hooks/use-inboundContact-qry.ts +96 -0
- package/hooks/use-integration-mtn.ts +77 -0
- package/hooks/use-integration-qry.ts +30 -0
- package/hooks/use-log-mtn.ts +77 -61
- package/hooks/use-log-qry.ts +99 -72
- package/hooks/use-organization-mtn.ts +409 -80
- package/hooks/use-organization-qry.ts +211 -92
- package/hooks/use-schedule-mtn.ts +416 -0
- package/hooks/use-schedule-qry.ts +157 -0
- package/hooks/use-sheet-mtn.ts +367 -0
- package/hooks/use-sheet-qry.ts +440 -0
- package/hooks/use-storage-mtn.ts +83 -42
- package/hooks/use-storage-qry.ts +104 -13
- package/hooks/use-workflow-mtn.ts +55 -0
- package/hooks/use-workflow-qry.ts +230 -0
- package/loaders/campaign.ts +137 -0
- package/package.json +94 -52
- package/sse.ts +158 -105
- package/tsconfig.json +13 -0
- package/types.d.ts +60 -29
- package/utils.ts +77 -50
- package/gql/fragments/actionFragments.ts +0 -16
- package/gql/fragments/productFragments.ts +0 -63
- package/gql/fragments/reportFragments.ts +0 -48
- package/gql/mutations/billingMutations.ts +0 -34
- package/gql/queries/productQueries.ts +0 -70
- package/gql/queries/reportQueries.ts +0 -66
- package/hooks/use-product-qry.ts +0 -109
- package/hooks/use-report-qry.ts +0 -69
package/hooks/index.ts
CHANGED
|
@@ -1,48 +1,97 @@
|
|
|
1
1
|
import { getENVVariable } from '@jsb188/app';
|
|
2
|
-
import type {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import
|
|
12
|
-
|
|
2
|
+
import type {
|
|
3
|
+
ServerErrorObj,
|
|
4
|
+
SimpleErrorType,
|
|
5
|
+
} from '@jsb188/app/types/app.d.ts';
|
|
6
|
+
import {
|
|
7
|
+
getAuthToken,
|
|
8
|
+
managedAccessTokensShareBinding,
|
|
9
|
+
normalizeServerError,
|
|
10
|
+
} from '@jsb188/app/utils/api.ts';
|
|
11
|
+
import { delay, makeVariablesKey } from '@jsb188/app/utils/logic.ts';
|
|
12
|
+
import {
|
|
13
|
+
queryCacheKeyMatchesResetTarget,
|
|
14
|
+
type QueryResetTarget,
|
|
15
|
+
} from '@jsb188/app/utils/queryReset.ts';
|
|
16
|
+
import {
|
|
17
|
+
isServerErrorGQL,
|
|
18
|
+
isTransientServerError,
|
|
19
|
+
} from '@jsb188/graphql/utils';
|
|
20
|
+
import {
|
|
21
|
+
useConnectedToServerValue,
|
|
22
|
+
useOptimisticConnectedToServerValue,
|
|
23
|
+
useScreenIsFocusedValue,
|
|
24
|
+
} from '@jsb188/react/states';
|
|
25
|
+
import {
|
|
26
|
+
useCallback,
|
|
27
|
+
useEffect,
|
|
28
|
+
useLayoutEffect,
|
|
29
|
+
useMemo,
|
|
30
|
+
useRef,
|
|
31
|
+
useState,
|
|
32
|
+
useSyncExternalStore,
|
|
33
|
+
} from 'react';
|
|
34
|
+
import { QUERY_EXPIRE_TIMES } from '../cache/config.ts';
|
|
35
|
+
import { EAGER_QUERY_MAP } from '../gql/eagerQueryMap.ts';
|
|
36
|
+
import {
|
|
37
|
+
checkDataCompleteness,
|
|
38
|
+
clearQueryResetStatus,
|
|
39
|
+
fetchCachedData,
|
|
40
|
+
getFragmentVersionStamp,
|
|
41
|
+
getNextQueryLastUpdatedCount,
|
|
42
|
+
getQueryLastFetchedAt,
|
|
43
|
+
getQueryRefreshTime,
|
|
44
|
+
loadDataFromCache,
|
|
45
|
+
loadFragment,
|
|
46
|
+
removeStaleCache,
|
|
47
|
+
} from '../cache/index.ts';
|
|
48
|
+
import { graphqlRequest } from '../client/request.ts';
|
|
49
|
+
import type {
|
|
50
|
+
AnyModalPopUpFn,
|
|
51
|
+
GraphQLHandlers,
|
|
52
|
+
GraphQLQueryOptions,
|
|
53
|
+
OnCompletedGQLFn,
|
|
54
|
+
OnErrorGQLFn,
|
|
55
|
+
UpdateDataObserverArgs,
|
|
56
|
+
UpdateObserversFn,
|
|
57
|
+
} from '../types.d.ts';
|
|
13
58
|
|
|
14
59
|
/**
|
|
15
60
|
* Types; mutation
|
|
16
61
|
*/
|
|
17
62
|
|
|
18
|
-
export type GraphQLMutationFn = (
|
|
63
|
+
export type GraphQLMutationFn = (
|
|
64
|
+
graphqlOptions?: GraphQLRequestOptions,
|
|
65
|
+
triedCount?: number,
|
|
66
|
+
) => Promise<any>;
|
|
19
67
|
|
|
20
68
|
type GraphQLMutationOptions = Partial<{
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
69
|
+
checkMountedBeforeCallback: boolean;
|
|
70
|
+
authToken: string;
|
|
71
|
+
retryCount: number;
|
|
72
|
+
variables: Record<string, any> | null;
|
|
73
|
+
cacheMap: any;
|
|
74
|
+
cachePolicy: 'default' | 'no-store';
|
|
75
|
+
openModalPopUp: AnyModalPopUpFn | null;
|
|
76
|
+
initialError: any;
|
|
77
|
+
onCompleted: OnCompletedGQLFn;
|
|
78
|
+
onError: OnErrorGQLFn;
|
|
30
79
|
}>;
|
|
31
80
|
|
|
32
81
|
type GraphQLMutationResult = {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
82
|
+
data: any | null;
|
|
83
|
+
variables: Record<string, any> | null;
|
|
84
|
+
saving: boolean;
|
|
85
|
+
error: ServerErrorObj | null;
|
|
86
|
+
mutationCount: number;
|
|
38
87
|
};
|
|
39
88
|
|
|
40
89
|
type GraphQLMutation = [
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
90
|
+
GraphQLMutationFn,
|
|
91
|
+
GraphQLMutationResult,
|
|
92
|
+
GraphQLHandlers,
|
|
93
|
+
UpdateObserversFn,
|
|
94
|
+
React.MutableRefObject<Record<string, any>>,
|
|
46
95
|
];
|
|
47
96
|
|
|
48
97
|
/**
|
|
@@ -50,24 +99,41 @@ type GraphQLMutation = [
|
|
|
50
99
|
*/
|
|
51
100
|
|
|
52
101
|
type GraphQLRequestOptions = {
|
|
53
|
-
|
|
102
|
+
variables?: Record<string, any> | null;
|
|
54
103
|
};
|
|
55
104
|
|
|
56
105
|
type GraphQLQueryResult = {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
106
|
+
data: any | null;
|
|
107
|
+
variables?: Record<string, any> | null;
|
|
108
|
+
loading: boolean;
|
|
109
|
+
error: ServerErrorObj | null;
|
|
110
|
+
refetch: () => void;
|
|
111
|
+
fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
|
|
112
|
+
queryName: string;
|
|
113
|
+
queryKey: string;
|
|
114
|
+
refreshTime: string;
|
|
115
|
+
resetOnlyTime: string;
|
|
116
|
+
variablesKey: string;
|
|
117
|
+
updatedCount: number;
|
|
118
|
+
updateObservers: UpdateObserversFn;
|
|
119
|
+
connectedToServer: boolean;
|
|
120
|
+
recovering: boolean;
|
|
121
|
+
screenIsFocused: boolean;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
type GraphQLQueryValues = {
|
|
125
|
+
data: any;
|
|
126
|
+
variables?: Record<string, any> | null;
|
|
127
|
+
loading: boolean;
|
|
128
|
+
error: ServerErrorObj | null;
|
|
129
|
+
lastUpdatedCount: number;
|
|
130
|
+
lastRefreshTriggerTime: string;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
type GraphQLQueryOutput = {
|
|
134
|
+
queryKey: string;
|
|
135
|
+
refreshTime: string;
|
|
136
|
+
data: any | null;
|
|
71
137
|
};
|
|
72
138
|
|
|
73
139
|
/**
|
|
@@ -75,16 +141,214 @@ type GraphQLQueryResult = {
|
|
|
75
141
|
*/
|
|
76
142
|
|
|
77
143
|
const QRY_TRACKER = new Map();
|
|
144
|
+
const QRY_PROMISES = new Map<string, Promise<any>>();
|
|
145
|
+
const FRAGMENT_OBSERVER_LISTENERS = new Map<
|
|
146
|
+
string,
|
|
147
|
+
Set<(fragmentIds: string[]) => void>
|
|
148
|
+
>();
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Keyed query observer registry. Each mounted useQuery() subscribes with a
|
|
152
|
+
* match predicate for its own query keys, so a query event only re-renders
|
|
153
|
+
* the hooks it can actually affect (previously a single global Jotai atom
|
|
154
|
+
* re-rendered every mounted query hook on every event).
|
|
155
|
+
*/
|
|
156
|
+
|
|
157
|
+
type QueryObserverEventObj = {
|
|
158
|
+
count: number;
|
|
159
|
+
eventSequence: number;
|
|
160
|
+
name: string;
|
|
161
|
+
// Present when the reset came from a structured target; matching uses this
|
|
162
|
+
// rather than the name, which is only a stable identity string
|
|
163
|
+
target?: QueryResetTarget | null;
|
|
164
|
+
forceRefetch: boolean;
|
|
165
|
+
resetOnly: boolean;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const QUERY_OBSERVER_LISTENERS = new Set<
|
|
169
|
+
(event: QueryObserverEventObj) => void
|
|
170
|
+
>();
|
|
171
|
+
|
|
172
|
+
// The last published event is retained so a hook mounting later still sees
|
|
173
|
+
// it on first render; this is what lets a freshly mounted query pick up a
|
|
174
|
+
// RESET_TIME entry that was set while it was unmounted.
|
|
175
|
+
let LAST_QUERY_OBSERVER_EVENT: QueryObserverEventObj = {
|
|
176
|
+
count: 0,
|
|
177
|
+
eventSequence: 0,
|
|
178
|
+
name: '',
|
|
179
|
+
target: null,
|
|
180
|
+
forceRefetch: false,
|
|
181
|
+
resetOnly: false,
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const FILE_CONSTANTS = {
|
|
185
|
+
transientRetryBaseMs: 500,
|
|
186
|
+
transientRetryJitterMs: 250,
|
|
187
|
+
transientRetryMaximumMs: 10000,
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Check whether one query's cached data is older than its freshness window
|
|
192
|
+
* (options.persistTime, falling back to the query's expire time). Data that
|
|
193
|
+
* never came from the network in this session or persisted snapshot is
|
|
194
|
+
* always stale.
|
|
195
|
+
*/
|
|
196
|
+
|
|
197
|
+
function queryDataIsStale(
|
|
198
|
+
queryName: string,
|
|
199
|
+
queryKey: string,
|
|
200
|
+
persistTime?: number,
|
|
201
|
+
): boolean {
|
|
202
|
+
const lastFetchedAt = getQueryLastFetchedAt(queryKey);
|
|
203
|
+
|
|
204
|
+
if (!lastFetchedAt) {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const freshnessWindow =
|
|
209
|
+
typeof persistTime === 'number'
|
|
210
|
+
? persistTime
|
|
211
|
+
: QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
|
|
212
|
+
|
|
213
|
+
return Date.now() - lastFetchedAt > freshnessWindow;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Return a unique id for one mounted query hook instance.
|
|
218
|
+
*/
|
|
219
|
+
function makeQueryHookId() {
|
|
220
|
+
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Return GraphQL result data wrapped under its operation name.
|
|
225
|
+
*/
|
|
226
|
+
function getQueryDataFromAPIResult(queryName: string, apiResult: any) {
|
|
227
|
+
if (
|
|
228
|
+
!apiResult ||
|
|
229
|
+
apiResult.aborted ||
|
|
230
|
+
apiResult.error ||
|
|
231
|
+
apiResult[queryName] === undefined
|
|
232
|
+
) {
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
[queryName]: apiResult[queryName],
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Convert reactive fragment observe entries into exact fragment observer keys.
|
|
243
|
+
*/
|
|
244
|
+
|
|
245
|
+
function getReactiveFragmentObserveKeys(
|
|
246
|
+
observe: Array<string | [string, string | null]>,
|
|
247
|
+
) {
|
|
248
|
+
return observe
|
|
249
|
+
.map((key) => {
|
|
250
|
+
return Array.isArray(key) ? key[0] : key;
|
|
251
|
+
})
|
|
252
|
+
.filter(Boolean);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Subscribe to exact fragment observer keys.
|
|
257
|
+
*/
|
|
258
|
+
|
|
259
|
+
function subscribeFragmentObserverKeys(
|
|
260
|
+
fragmentIds: string[],
|
|
261
|
+
listener: (fragmentIds: string[]) => void,
|
|
262
|
+
) {
|
|
263
|
+
for (const fragmentId of fragmentIds) {
|
|
264
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId) || new Set();
|
|
265
|
+
listeners.add(listener);
|
|
266
|
+
FRAGMENT_OBSERVER_LISTENERS.set(fragmentId, listeners);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return () => {
|
|
270
|
+
for (const fragmentId of fragmentIds) {
|
|
271
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
|
|
272
|
+
listeners?.delete(listener);
|
|
273
|
+
|
|
274
|
+
if (!listeners?.size) {
|
|
275
|
+
FRAGMENT_OBSERVER_LISTENERS.delete(fragmentId);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Subscribe to exact reactive fragment keys from outside the hook layer.
|
|
283
|
+
* Used by feature stores (e.g. the sheet cell store) that consume realtime
|
|
284
|
+
* fragment patches directly instead of through useReactiveFragment.
|
|
285
|
+
* Returns the unsubscribe function.
|
|
286
|
+
*/
|
|
287
|
+
|
|
288
|
+
export function observeReactiveFragments(
|
|
289
|
+
fragmentIds: string[],
|
|
290
|
+
listener: (fragmentIds: string[]) => void,
|
|
291
|
+
) {
|
|
292
|
+
return subscribeFragmentObserverKeys(fragmentIds, listener);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Notify keyed reactive fragment subscribers for only the changed fragment ids.
|
|
297
|
+
*/
|
|
298
|
+
|
|
299
|
+
function notifyFragmentObserverListeners(fragmentIds: string[]) {
|
|
300
|
+
const notifiedListeners = new Set<(fragmentIds: string[]) => void>();
|
|
301
|
+
|
|
302
|
+
for (const fragmentId of fragmentIds) {
|
|
303
|
+
const listeners = FRAGMENT_OBSERVER_LISTENERS.get(fragmentId);
|
|
304
|
+
|
|
305
|
+
listeners?.forEach((listener) => {
|
|
306
|
+
if (!notifiedListeners.has(listener)) {
|
|
307
|
+
notifiedListeners.add(listener);
|
|
308
|
+
listener(fragmentIds);
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Observe only the exact fragment keys needed by one reactive fragment hook.
|
|
316
|
+
*/
|
|
317
|
+
|
|
318
|
+
function useFragmentKeyObserver(
|
|
319
|
+
observe: Array<string | [string, string | null]>,
|
|
320
|
+
) {
|
|
321
|
+
const observeStr = getReactiveFragmentObserveKeys(observe).join(',');
|
|
322
|
+
const observeKeys = useMemo(
|
|
323
|
+
() => observeStr.split(',').filter(Boolean),
|
|
324
|
+
[observeStr],
|
|
325
|
+
);
|
|
326
|
+
const [fragmentObserver, setFragmentObserver] = useState({
|
|
327
|
+
count: 0,
|
|
328
|
+
list: [] as string[],
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
useEffect(() => {
|
|
332
|
+
return subscribeFragmentObserverKeys(observeKeys, (fragmentIds) => {
|
|
333
|
+
setFragmentObserver((prev) => ({
|
|
334
|
+
count: prev.count + 1,
|
|
335
|
+
list: fragmentIds,
|
|
336
|
+
}));
|
|
337
|
+
});
|
|
338
|
+
}, [observeKeys]);
|
|
339
|
+
|
|
340
|
+
return fragmentObserver;
|
|
341
|
+
}
|
|
78
342
|
|
|
79
343
|
/**
|
|
80
344
|
* Global; unset query tracker
|
|
81
345
|
*/
|
|
82
346
|
|
|
83
347
|
function unsetQueryTracker(queryName: string, unique: string | null) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
348
|
+
const currentHookId = QRY_TRACKER.get(queryName);
|
|
349
|
+
if (currentHookId === unique) {
|
|
350
|
+
QRY_TRACKER.delete(queryName);
|
|
351
|
+
}
|
|
88
352
|
}
|
|
89
353
|
|
|
90
354
|
/**
|
|
@@ -92,33 +356,166 @@ function unsetQueryTracker(queryName: string, unique: string | null) {
|
|
|
92
356
|
*/
|
|
93
357
|
|
|
94
358
|
function getRetryDelay(triedCount: number): number {
|
|
95
|
-
|
|
359
|
+
return 1500 * Math.pow(2, triedCount);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Return a capped, jittered delay for retrying one temporary server failure.
|
|
364
|
+
*/
|
|
365
|
+
function getTransientRetryDelay(attemptCount: number): number {
|
|
366
|
+
const exponentialDelay = Math.min(
|
|
367
|
+
FILE_CONSTANTS.transientRetryMaximumMs,
|
|
368
|
+
FILE_CONSTANTS.transientRetryBaseMs * 2 ** attemptCount,
|
|
369
|
+
);
|
|
370
|
+
|
|
371
|
+
return Math.min(
|
|
372
|
+
FILE_CONSTANTS.transientRetryMaximumMs,
|
|
373
|
+
exponentialDelay +
|
|
374
|
+
Math.floor(Math.random() * FILE_CONSTANTS.transientRetryJitterMs),
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Return whether a delayed retry still belongs to the same browser login or
|
|
380
|
+
* to a refreshed token for that exact managed account session.
|
|
381
|
+
*/
|
|
382
|
+
function authContextMatchesRetryToken(
|
|
383
|
+
retryToken: string | null,
|
|
384
|
+
currentToken: string | null,
|
|
385
|
+
) {
|
|
386
|
+
return (
|
|
387
|
+
retryToken === currentToken ||
|
|
388
|
+
Boolean(
|
|
389
|
+
retryToken &&
|
|
390
|
+
currentToken &&
|
|
391
|
+
managedAccessTokensShareBinding(retryToken, currentToken),
|
|
392
|
+
)
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Publish a data observer event to keyed query/fragment subscribers.
|
|
398
|
+
* Works outside React (websocket handlers, imperative cache updates).
|
|
399
|
+
*/
|
|
400
|
+
|
|
401
|
+
export function updateDataObservers(args: UpdateDataObserverArgs) {
|
|
402
|
+
if (args.queryId) {
|
|
403
|
+
LAST_QUERY_OBSERVER_EVENT = {
|
|
404
|
+
count:
|
|
405
|
+
(LAST_QUERY_OBSERVER_EVENT.name === args.queryId
|
|
406
|
+
? LAST_QUERY_OBSERVER_EVENT.count
|
|
407
|
+
: 0) + 1,
|
|
408
|
+
eventSequence: (LAST_QUERY_OBSERVER_EVENT.eventSequence || 0) + 1,
|
|
409
|
+
name: args.queryId as string,
|
|
410
|
+
target: args.queryTarget || null,
|
|
411
|
+
forceRefetch: !!args.forceRefetch,
|
|
412
|
+
resetOnly: !!args.resetOnly,
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const event = LAST_QUERY_OBSERVER_EVENT;
|
|
416
|
+
QUERY_OBSERVER_LISTENERS.forEach((listener) => {
|
|
417
|
+
listener(event);
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (args.fragmentIds?.length) {
|
|
422
|
+
notifyFragmentObserverListeners(args.fragmentIds as string[]);
|
|
423
|
+
}
|
|
96
424
|
}
|
|
97
425
|
|
|
98
426
|
/**
|
|
99
427
|
* Update data observer
|
|
428
|
+
* Kept as a hook for call-site compatibility; the returned function is the
|
|
429
|
+
* stable module-level publisher.
|
|
100
430
|
*/
|
|
101
431
|
|
|
102
432
|
export function useUpdateObservers(): UpdateObserversFn {
|
|
103
|
-
|
|
104
|
-
|
|
433
|
+
return updateDataObservers;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Check whether one query observer event can affect a query hook mounted
|
|
438
|
+
* with the given document + variables key. Mirrors the matching rules in
|
|
439
|
+
* useWatchQuery(); slight over-matching is safe (it only re-runs the memo),
|
|
440
|
+
* under-matching would drop updates.
|
|
441
|
+
*/
|
|
105
442
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
443
|
+
function queryObserverEventMatchesQuery(
|
|
444
|
+
event: QueryObserverEventObj,
|
|
445
|
+
query: any,
|
|
446
|
+
variablesKey: string,
|
|
447
|
+
): boolean {
|
|
448
|
+
const eventName = event.name;
|
|
449
|
+
if (!eventName) {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const queryDefs = query.definitions.filter(
|
|
454
|
+
(d: any) => d.kind === 'OperationDefinition',
|
|
455
|
+
);
|
|
456
|
+
|
|
457
|
+
// A pending force-refetch reset for this query must always be picked up
|
|
458
|
+
const firstQueryName = queryDefs?.[0]?.name?.value;
|
|
459
|
+
if (firstQueryName && getQueryRefreshTime(firstQueryName, variablesKey)) {
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
return queryDefs.some((d: any) => {
|
|
464
|
+
const queryName = d.name.value;
|
|
465
|
+
const fullQueryKey = `#${queryName}:${variablesKey}`;
|
|
466
|
+
|
|
467
|
+
if (event.target) {
|
|
468
|
+
return queryCacheKeyMatchesResetTarget(fullQueryKey, event.target);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
if (eventName.startsWith('^')) {
|
|
472
|
+
try {
|
|
473
|
+
return new RegExp(eventName).test(fullQueryKey);
|
|
474
|
+
} catch (_err) {
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return (
|
|
480
|
+
eventName === fullQueryKey ||
|
|
481
|
+
eventName === `#${queryName}:` ||
|
|
482
|
+
fullQueryKey.startsWith(eventName)
|
|
483
|
+
);
|
|
484
|
+
});
|
|
485
|
+
}
|
|
114
486
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
487
|
+
/**
|
|
488
|
+
* Subscribe one query hook to only the observer events that match its query.
|
|
489
|
+
*/
|
|
490
|
+
|
|
491
|
+
function useQueryObserverEvent(
|
|
492
|
+
query: any,
|
|
493
|
+
variablesKey: string,
|
|
494
|
+
): QueryObserverEventObj {
|
|
495
|
+
const [event, setEvent] = useState(LAST_QUERY_OBSERVER_EVENT);
|
|
496
|
+
|
|
497
|
+
useEffect(() => {
|
|
498
|
+
const listener = (nextEvent: QueryObserverEventObj) => {
|
|
499
|
+
if (queryObserverEventMatchesQuery(nextEvent, query, variablesKey)) {
|
|
500
|
+
setEvent(nextEvent);
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
QUERY_OBSERVER_LISTENERS.add(listener);
|
|
505
|
+
|
|
506
|
+
// Deliver anything published between render and subscription
|
|
507
|
+
setEvent((currentEvent: QueryObserverEventObj) =>
|
|
508
|
+
currentEvent === LAST_QUERY_OBSERVER_EVENT
|
|
509
|
+
? currentEvent
|
|
510
|
+
: LAST_QUERY_OBSERVER_EVENT,
|
|
511
|
+
);
|
|
512
|
+
|
|
513
|
+
return () => {
|
|
514
|
+
QUERY_OBSERVER_LISTENERS.delete(listener);
|
|
515
|
+
};
|
|
516
|
+
}, [variablesKey]);
|
|
517
|
+
|
|
518
|
+
return event;
|
|
122
519
|
}
|
|
123
520
|
|
|
124
521
|
/**
|
|
@@ -126,347 +523,470 @@ export function useUpdateObservers(): UpdateObserversFn {
|
|
|
126
523
|
*/
|
|
127
524
|
|
|
128
525
|
export function useWatchQuery(
|
|
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
|
-
|
|
526
|
+
query: any,
|
|
527
|
+
variablesKey: string,
|
|
528
|
+
lastUpdatedCount: number,
|
|
529
|
+
loading: boolean,
|
|
530
|
+
) {
|
|
531
|
+
const qryObserver = useQueryObserverEvent(query, variablesKey);
|
|
532
|
+
const [qryReset, setQryReset] = useState({
|
|
533
|
+
triggerTime: '',
|
|
534
|
+
refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
|
|
535
|
+
refreshTimeActive: '', // This value resets when loading starts
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
const queryWatcher = useMemo<[number, boolean, string, string]>(() => {
|
|
539
|
+
if (qryObserver.name) {
|
|
540
|
+
const queryDefs = query.definitions.filter(
|
|
541
|
+
(d: any) => d.kind === 'OperationDefinition',
|
|
542
|
+
);
|
|
543
|
+
const queryName = queryDefs?.[0]?.name?.value;
|
|
544
|
+
|
|
545
|
+
if (queryName) {
|
|
546
|
+
const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
|
|
547
|
+
|
|
548
|
+
if (qryTriggerTime) {
|
|
549
|
+
clearQueryResetStatus(queryName, variablesKey);
|
|
550
|
+
console.dev(
|
|
551
|
+
`... (1) Query [${queryName}:${variablesKey}] is being force refetched via observer.`,
|
|
552
|
+
);
|
|
553
|
+
return [lastUpdatedCount + 1, true, qryTriggerTime, ''];
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const matchedQry = queryDefs.find((d: any) => {
|
|
558
|
+
const queryName = d.name.value;
|
|
559
|
+
const fullQueryKey = `#${queryName}:${variablesKey}`;
|
|
560
|
+
const queryNameKey = `#${queryName}:`;
|
|
561
|
+
|
|
562
|
+
if (qryObserver.target) {
|
|
563
|
+
return queryCacheKeyMatchesResetTarget(
|
|
564
|
+
fullQueryKey,
|
|
565
|
+
qryObserver.target,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
if (qryObserver.name.startsWith('^')) {
|
|
570
|
+
try {
|
|
571
|
+
return new RegExp(qryObserver.name).test(fullQueryKey);
|
|
572
|
+
} catch (_err) {
|
|
573
|
+
return false;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return (
|
|
578
|
+
qryObserver.name === fullQueryKey ||
|
|
579
|
+
qryObserver.name === queryNameKey ||
|
|
580
|
+
fullQueryKey.startsWith(qryObserver.name)
|
|
581
|
+
);
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
if (!matchedQry) {
|
|
585
|
+
return [lastUpdatedCount, false, '', ''];
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const matchedQueryName = matchedQry.name.value;
|
|
589
|
+
const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
|
|
590
|
+
const forceRefetch = !!qryObserver.forceRefetch;
|
|
591
|
+
const resetOnlyTime = qryObserver.resetOnly
|
|
592
|
+
? String(qryObserver.eventSequence)
|
|
593
|
+
: '';
|
|
594
|
+
|
|
595
|
+
let newUpdatedCount =
|
|
596
|
+
qryObserver.name === matchedQueryId || forceRefetch
|
|
597
|
+
? qryObserver.count
|
|
598
|
+
: 0;
|
|
599
|
+
if (forceRefetch) {
|
|
600
|
+
newUpdatedCount += 1;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
if (forceRefetch) {
|
|
604
|
+
console.dev(
|
|
605
|
+
`... (2) Query [${matchedQueryId}] is being force refetched via observer.`,
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
return [newUpdatedCount, forceRefetch, '', resetOnlyTime];
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
return [lastUpdatedCount, false, '', ''];
|
|
613
|
+
}, [lastUpdatedCount, qryObserver]);
|
|
614
|
+
|
|
615
|
+
useEffect(() => {
|
|
616
|
+
if (!loading) {
|
|
617
|
+
if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
|
|
618
|
+
setQryReset((prev) => ({
|
|
619
|
+
...prev,
|
|
620
|
+
refreshTime: qryReset.triggerTime,
|
|
621
|
+
refreshTimeActive: qryReset.triggerTime,
|
|
622
|
+
}));
|
|
623
|
+
} else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
|
|
624
|
+
setQryReset((prev) => ({
|
|
625
|
+
...prev,
|
|
626
|
+
triggerTime: queryWatcher[2],
|
|
627
|
+
}));
|
|
628
|
+
}
|
|
629
|
+
} else if (qryReset.refreshTimeActive) {
|
|
630
|
+
setQryReset((prev) => ({
|
|
631
|
+
...prev,
|
|
632
|
+
triggerTime: '',
|
|
633
|
+
refreshTimeActive: '',
|
|
634
|
+
}));
|
|
635
|
+
}
|
|
636
|
+
}, [queryWatcher[2], loading]);
|
|
637
|
+
|
|
638
|
+
// console.log('refreshTime:', refreshTime + queryWatcher[0]);
|
|
639
|
+
|
|
640
|
+
return {
|
|
641
|
+
updatedCount: queryWatcher[0],
|
|
642
|
+
forceRefetch: queryWatcher[1],
|
|
643
|
+
resetOnlyTime: queryWatcher[3],
|
|
644
|
+
qryReset,
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/*
|
|
649
|
+
* Merge one current document with the latest values from its observed fragment
|
|
650
|
+
* keys. Fragment values win because websocket updates can be newer than the
|
|
651
|
+
* query result that supplied the document base.
|
|
652
|
+
*/
|
|
653
|
+
function getReactiveFragmentData(
|
|
654
|
+
data: any,
|
|
655
|
+
observe: Array<string | [string, string | null]>,
|
|
656
|
+
mainPrioritizedFields?: string[],
|
|
657
|
+
) {
|
|
658
|
+
let nextData = data;
|
|
659
|
+
|
|
660
|
+
observe.forEach((key) => {
|
|
661
|
+
const isMapped = Array.isArray(key);
|
|
662
|
+
const fragmentData = loadFragment(
|
|
663
|
+
isMapped ? key[0] : key,
|
|
664
|
+
mainPrioritizedFields,
|
|
665
|
+
);
|
|
666
|
+
|
|
667
|
+
if (!fragmentData) {
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (isMapped) {
|
|
671
|
+
if (key[1]) {
|
|
672
|
+
nextData = {
|
|
673
|
+
...nextData,
|
|
674
|
+
[key[1]]: fragmentData,
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
nextData = {
|
|
681
|
+
...nextData,
|
|
682
|
+
...fragmentData,
|
|
683
|
+
};
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
return nextData;
|
|
216
687
|
}
|
|
217
688
|
|
|
218
689
|
/**
|
|
219
690
|
* Hook for reactive fragment data
|
|
691
|
+
* This function will return the cached data if it exists, even if the `data` param is null.
|
|
220
692
|
*/
|
|
221
693
|
|
|
222
694
|
export function useReactiveFragment(
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
695
|
+
data: any,
|
|
696
|
+
observe: Array<string | [string, string | null]>,
|
|
697
|
+
qryObsCount?: number | boolean,
|
|
698
|
+
otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
|
|
699
|
+
mainPrioritizedFields?: string[],
|
|
700
|
+
ignoreIDWarning?: boolean,
|
|
701
|
+
isTest?: boolean,
|
|
229
702
|
) {
|
|
703
|
+
const fragmentObserver = useFragmentKeyObserver(observe);
|
|
704
|
+
const frgObsCount = fragmentObserver.count;
|
|
705
|
+
const dataId = data?.id;
|
|
706
|
+
|
|
707
|
+
// Version stamp of the observed fragments at the last rebuild; notifications
|
|
708
|
+
// that did not actually change any observed fragment are skipped without a
|
|
709
|
+
// state update (deep-equal cache writes never bump fragment versions).
|
|
710
|
+
const lastBuildStampRef = useRef('');
|
|
711
|
+
|
|
712
|
+
const [changedData, setChangedData] = useState<any>(() => {
|
|
713
|
+
return {
|
|
714
|
+
fragmentUpdatedCount: frgObsCount,
|
|
715
|
+
queryUpdatedCount: qryObsCount,
|
|
716
|
+
data: getReactiveFragmentData(data, observe, mainPrioritizedFields),
|
|
717
|
+
};
|
|
718
|
+
});
|
|
719
|
+
|
|
720
|
+
if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
|
|
721
|
+
// this is fine because it will only run in development and never truly be conditional
|
|
722
|
+
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
723
|
+
useEffect(() => {
|
|
724
|
+
if (
|
|
725
|
+
// getENVVariable('NODE_ENV') === 'development' &&
|
|
726
|
+
dataId &&
|
|
727
|
+
changedData.data?.id &&
|
|
728
|
+
dataId !== changedData.data?.id
|
|
729
|
+
) {
|
|
730
|
+
console.warn(
|
|
731
|
+
`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`,
|
|
732
|
+
);
|
|
733
|
+
console.warn(
|
|
734
|
+
'This can result in invalid merged data. Use key={id} to avoid this error.',
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
}, [changedData.data?.id]);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
useEffect(() => {
|
|
741
|
+
// NOTE: I tried this with Preact's effect()
|
|
742
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
743
|
+
// I only solved it by using useEffect()
|
|
744
|
+
const idsChanged =
|
|
745
|
+
!dataId ||
|
|
746
|
+
changedData.data?.id !== dataId ||
|
|
747
|
+
// This is absolutely needed for the chat clientId system to work properly;
|
|
748
|
+
// Otherwise messages will be stuck in "not sent" state.
|
|
749
|
+
(changedData.data?.clientId &&
|
|
750
|
+
changedData.data?.clientId !== data.clientId);
|
|
751
|
+
const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
|
|
752
|
+
|
|
753
|
+
const forceReactive = otherCheck?.(changedData.data, fragmentObserver.list);
|
|
754
|
+
|
|
755
|
+
if (
|
|
756
|
+
idsChanged ||
|
|
757
|
+
forceReactive ||
|
|
758
|
+
((changedData.data || data) &&
|
|
759
|
+
(frgObsCount !== changedData.fragmentUpdatedCount || queryDataChanged))
|
|
760
|
+
) {
|
|
761
|
+
// When only a fragment notification arrived, skip the rebuild if none
|
|
762
|
+
// of the observed fragments actually changed since the last build.
|
|
763
|
+
if (!idsChanged && !queryDataChanged && !forceReactive) {
|
|
764
|
+
const observedStamp = getFragmentVersionStamp(
|
|
765
|
+
getReactiveFragmentObserveKeys(observe),
|
|
766
|
+
);
|
|
767
|
+
if (observedStamp === lastBuildStampRef.current) {
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const dataUpdated =
|
|
773
|
+
idsChanged ||
|
|
774
|
+
queryDataChanged ||
|
|
775
|
+
forceReactive ||
|
|
776
|
+
observe.some((key) => {
|
|
777
|
+
const isMapped = Array.isArray(key);
|
|
778
|
+
return isMapped
|
|
779
|
+
? fragmentObserver.list.includes(key[0])
|
|
780
|
+
: fragmentObserver.list.includes(key);
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
let newData: any;
|
|
784
|
+
if (dataUpdated) {
|
|
785
|
+
const baseData =
|
|
786
|
+
(idsChanged || queryDataChanged) && data
|
|
787
|
+
? data
|
|
788
|
+
: data
|
|
789
|
+
? { ...data, ...changedData.data }
|
|
790
|
+
: changedData.data;
|
|
791
|
+
newData = getReactiveFragmentData(
|
|
792
|
+
baseData,
|
|
793
|
+
observe,
|
|
794
|
+
mainPrioritizedFields,
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (newData) {
|
|
799
|
+
lastBuildStampRef.current = getFragmentVersionStamp(
|
|
800
|
+
getReactiveFragmentObserveKeys(observe),
|
|
801
|
+
);
|
|
802
|
+
setChangedData({
|
|
803
|
+
data: newData,
|
|
804
|
+
fragmentUpdatedCount: frgObsCount,
|
|
805
|
+
queryUpdatedCount: qryObsCount,
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}, [dataId, qryObsCount, frgObsCount]);
|
|
810
|
+
|
|
811
|
+
// This is not needed now, I think
|
|
812
|
+
// useEffect(() => {
|
|
813
|
+
// if (updateQueryCount && queryKey) {
|
|
814
|
+
// const updatedQueryData = loadQuery(queryKey);
|
|
815
|
+
// setChangedData({
|
|
816
|
+
// ...changedData,
|
|
817
|
+
// data: {
|
|
818
|
+
// ...changedData.data,
|
|
819
|
+
// ...updatedQueryData,
|
|
820
|
+
// },
|
|
821
|
+
// });
|
|
822
|
+
// }
|
|
823
|
+
// }, [updateQueryCount]);
|
|
824
|
+
|
|
825
|
+
// if (isTest) {
|
|
826
|
+
// console.log('dataId', dataId);
|
|
827
|
+
// console.log('1', changedData);
|
|
828
|
+
// console.log('2', data);
|
|
829
|
+
// }
|
|
830
|
+
|
|
831
|
+
if (data && qryObsCount !== changedData.queryUpdatedCount) {
|
|
832
|
+
return (
|
|
833
|
+
getReactiveFragmentData(data, observe, mainPrioritizedFields) ?? null
|
|
834
|
+
);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
return changedData.data ?? null;
|
|
838
|
+
}
|
|
230
839
|
|
|
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
|
-
if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
|
|
268
|
-
// this is fine because it will only run in development and never truly be conditional
|
|
269
|
-
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
270
|
-
useEffect(() => {
|
|
271
|
-
if (
|
|
272
|
-
// getENVVariable('NODE_ENV') === 'development' &&
|
|
273
|
-
dataId && changedData.data?.id &&
|
|
274
|
-
dataId !== changedData.data?.id
|
|
275
|
-
) {
|
|
276
|
-
console.warn(`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`);
|
|
277
|
-
console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
|
|
278
|
-
}
|
|
279
|
-
}, [changedData.data?.id]);
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
useEffect(() => {
|
|
283
|
-
|
|
284
|
-
// NOTE: I tried this with Preact's effect()
|
|
285
|
-
// But that caused the render to happen 3 times more, I don't know why.
|
|
286
|
-
// I only solved it by using useEffect()
|
|
287
|
-
const idsChanged = (
|
|
288
|
-
!dataId ||
|
|
289
|
-
changedData.data?.id !== dataId ||
|
|
290
|
-
(
|
|
291
|
-
// This is absolutely needed for the chat clientId system to work properly;
|
|
292
|
-
// Otherwise messages will be stuck in "not sent" state.
|
|
293
|
-
changedData.data?.clientId &&
|
|
294
|
-
changedData.data?.clientId !== data.clientId
|
|
295
|
-
)
|
|
296
|
-
);
|
|
297
|
-
|
|
298
|
-
const forceReactive = otherCheck && otherCheck(changedData.data, fragmentObserver.list);
|
|
299
|
-
|
|
300
|
-
if (
|
|
301
|
-
idsChanged ||
|
|
302
|
-
forceReactive || (
|
|
303
|
-
(changedData.data || data) &&
|
|
304
|
-
(
|
|
305
|
-
frgObsCount !== changedData.fragmentUpdatedCount ||
|
|
306
|
-
qryObsCount !== changedData.queryUpdatedCount
|
|
307
|
-
)
|
|
308
|
-
)
|
|
309
|
-
) {
|
|
310
|
-
|
|
311
|
-
const dataUpdated = (
|
|
312
|
-
idsChanged ||
|
|
313
|
-
forceReactive ||
|
|
314
|
-
observe.some((key) => {
|
|
315
|
-
const isMapped = Array.isArray(key);
|
|
316
|
-
return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
|
|
317
|
-
})
|
|
318
|
-
)
|
|
319
|
-
|
|
320
|
-
let newData;
|
|
321
|
-
if (dataUpdated) {
|
|
322
|
-
for (const key of observe) {
|
|
323
|
-
const isMapped = Array.isArray(key);
|
|
324
|
-
|
|
325
|
-
if (key) {
|
|
326
|
-
if (!newData) {
|
|
327
|
-
if (idsChanged) {
|
|
328
|
-
newData = data;
|
|
329
|
-
} else if (data) {
|
|
330
|
-
newData = {
|
|
331
|
-
...data,
|
|
332
|
-
...changedData.data,
|
|
333
|
-
};
|
|
334
|
-
} else {
|
|
335
|
-
newData = changedData.data;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
const fragmentData = loadFragment(isMapped ? key[0] : key);
|
|
340
|
-
|
|
341
|
-
// if (isTest) {
|
|
342
|
-
// console.log('fragmentKey', key);
|
|
343
|
-
// console.log('fragmentData', fragmentData);
|
|
344
|
-
// }
|
|
345
|
-
|
|
346
|
-
if (fragmentData) {
|
|
347
|
-
if (isMapped) {
|
|
348
|
-
if (key[1]) {
|
|
349
|
-
newData = {
|
|
350
|
-
...newData,
|
|
351
|
-
[key[1]]: fragmentData,
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
} else {
|
|
355
|
-
newData = {
|
|
356
|
-
...newData,
|
|
357
|
-
...fragmentData,
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
if (newData) {
|
|
366
|
-
setChangedData({
|
|
367
|
-
data: newData,
|
|
368
|
-
fragmentUpdatedCount: frgObsCount,
|
|
369
|
-
queryUpdatedCount: qryObsCount,
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}, [dataId, qryObsCount, frgObsCount]);
|
|
374
|
-
|
|
375
|
-
// This is not needed now, I think
|
|
376
|
-
// useEffect(() => {
|
|
377
|
-
// if (updateQueryCount && queryKey) {
|
|
378
|
-
// const updatedQueryData = loadQuery(queryKey);
|
|
379
|
-
// setChangedData({
|
|
380
|
-
// ...changedData,
|
|
381
|
-
// data: {
|
|
382
|
-
// ...changedData.data,
|
|
383
|
-
// ...updatedQueryData,
|
|
384
|
-
// },
|
|
385
|
-
// });
|
|
386
|
-
// }
|
|
387
|
-
// }, [updateQueryCount]);
|
|
388
|
-
|
|
389
|
-
// if (isTest) {
|
|
390
|
-
// console.log('dataId', dataId);
|
|
391
|
-
// console.log('1', changedData);
|
|
392
|
-
// console.log('2', data);
|
|
393
|
-
// }
|
|
394
|
-
|
|
395
|
-
return changedData.data ?? null;
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/**
|
|
399
|
-
* Observe query changes; but for Arrays
|
|
840
|
+
/**
|
|
841
|
+
* Merge mapped array data with the latest fragment cache values.
|
|
842
|
+
*/
|
|
843
|
+
|
|
844
|
+
function getReactiveFragmentMapData(
|
|
845
|
+
data: any[] | null,
|
|
846
|
+
observe?: string[] | null,
|
|
847
|
+
) {
|
|
848
|
+
if (!data || !observe?.length) {
|
|
849
|
+
return data;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
return data.map((item, i) => {
|
|
853
|
+
const key = observe[i];
|
|
854
|
+
if (!key) {
|
|
855
|
+
return item;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const fragmentData = loadFragment(key);
|
|
859
|
+
if (!fragmentData) {
|
|
860
|
+
return item;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
return {
|
|
864
|
+
...item,
|
|
865
|
+
...fragmentData,
|
|
866
|
+
};
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/*
|
|
871
|
+
* Observe fragment-backed arrays and synchronously rebase them when their
|
|
872
|
+
* owning query publishes a new same-shape result generation.
|
|
400
873
|
*/
|
|
401
874
|
|
|
402
875
|
export function useReactiveFragmentMap(
|
|
403
|
-
|
|
404
|
-
|
|
876
|
+
data: any[] | null,
|
|
877
|
+
fragmentName_: string,
|
|
878
|
+
qryObsCount?: number | boolean,
|
|
405
879
|
) {
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
880
|
+
const fragmentName = `$${fragmentName_}`;
|
|
881
|
+
const observeStr = useMemo<string>(
|
|
882
|
+
() => data?.map((item) => `${fragmentName}:${item.id}`).join(',') || '',
|
|
883
|
+
[data, fragmentName],
|
|
884
|
+
);
|
|
885
|
+
const observe = useMemo<string[]>(
|
|
886
|
+
() => observeStr.split(',').filter(Boolean),
|
|
887
|
+
[observeStr],
|
|
888
|
+
);
|
|
889
|
+
const observeIndex = useMemo<Map<string, number>>(() => {
|
|
890
|
+
const indexMap = new Map<string, number>();
|
|
891
|
+
|
|
892
|
+
observe.forEach((key: string, index: number) => {
|
|
893
|
+
indexMap.set(key, index);
|
|
894
|
+
});
|
|
895
|
+
|
|
896
|
+
return indexMap;
|
|
897
|
+
}, [observe]);
|
|
898
|
+
const fragmentObserver = useFragmentKeyObserver(observe);
|
|
899
|
+
|
|
900
|
+
// Version stamp of the observed fragments at the last rebuild; see
|
|
901
|
+
// useReactiveFragment() for the rationale.
|
|
902
|
+
const lastBuildStampRef = useRef('');
|
|
903
|
+
|
|
904
|
+
const [changedData, setChangedData] = useState({
|
|
905
|
+
count: fragmentObserver.count,
|
|
906
|
+
lastObserveStr: observeStr,
|
|
907
|
+
queryUpdatedCount: qryObsCount,
|
|
908
|
+
data: getReactiveFragmentMapData(data, observe),
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
useEffect(() => {
|
|
912
|
+
// NOTE: I tried this with Preact's effect()
|
|
913
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
914
|
+
// I only solved it by using useEffect()
|
|
915
|
+
|
|
916
|
+
const queryDataChanged = qryObsCount !== changedData.queryUpdatedCount;
|
|
917
|
+
const observedIdsChanged = changedData.lastObserveStr !== observeStr;
|
|
918
|
+
if (queryDataChanged || observedIdsChanged) {
|
|
919
|
+
lastBuildStampRef.current = getFragmentVersionStamp(observe);
|
|
920
|
+
setChangedData({
|
|
921
|
+
count: fragmentObserver.count,
|
|
922
|
+
data: getReactiveFragmentMapData(data, observe),
|
|
923
|
+
lastObserveStr: observeStr,
|
|
924
|
+
queryUpdatedCount: qryObsCount,
|
|
925
|
+
});
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (fragmentObserver.count === changedData.count) {
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// Skip the rebuild when none of the observed fragments actually changed
|
|
933
|
+
// since the last build (e.g. a deep-equal realtime echo).
|
|
934
|
+
const observedStamp = getFragmentVersionStamp(observe);
|
|
935
|
+
if (observedStamp === lastBuildStampRef.current) {
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const dataToUpdate = changedData.data || data;
|
|
940
|
+
let newData: any;
|
|
941
|
+
|
|
942
|
+
for (const key of fragmentObserver.list) {
|
|
943
|
+
const index = observeIndex.get(key);
|
|
944
|
+
if (index === undefined || !dataToUpdate?.[index]) {
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
const fragmentData = loadFragment(key);
|
|
949
|
+
if (!fragmentData) {
|
|
950
|
+
continue;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (!newData) {
|
|
954
|
+
newData = dataToUpdate.slice(0);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
newData[index] = {
|
|
958
|
+
...newData[index],
|
|
959
|
+
...fragmentData,
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
lastBuildStampRef.current = observedStamp;
|
|
964
|
+
|
|
965
|
+
if (newData) {
|
|
966
|
+
setChangedData({
|
|
967
|
+
...changedData,
|
|
968
|
+
count: fragmentObserver.count,
|
|
969
|
+
data: newData,
|
|
970
|
+
queryUpdatedCount: qryObsCount,
|
|
971
|
+
});
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
setChangedData({
|
|
976
|
+
...changedData,
|
|
977
|
+
count: fragmentObserver.count,
|
|
978
|
+
queryUpdatedCount: qryObsCount,
|
|
979
|
+
});
|
|
980
|
+
}, [fragmentObserver.count, observeStr, qryObsCount]);
|
|
981
|
+
|
|
982
|
+
if (
|
|
983
|
+
changedData.lastObserveStr !== observeStr ||
|
|
984
|
+
changedData.queryUpdatedCount !== qryObsCount
|
|
985
|
+
) {
|
|
986
|
+
return getReactiveFragmentMapData(data, observe);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
return changedData.data || data;
|
|
470
990
|
}
|
|
471
991
|
|
|
472
992
|
/**
|
|
@@ -474,170 +994,484 @@ export function useReactiveFragmentMap(
|
|
|
474
994
|
*/
|
|
475
995
|
|
|
476
996
|
export function useMutation(
|
|
477
|
-
|
|
478
|
-
|
|
997
|
+
mutation: any,
|
|
998
|
+
options?: GraphQLMutationOptions,
|
|
479
999
|
): GraphQLMutation {
|
|
1000
|
+
const {
|
|
1001
|
+
onCompleted,
|
|
1002
|
+
onError,
|
|
1003
|
+
openModalPopUp,
|
|
1004
|
+
initialError,
|
|
1005
|
+
checkMountedBeforeCallback,
|
|
1006
|
+
cachePolicy,
|
|
1007
|
+
} = options || {};
|
|
1008
|
+
const updateObservers = useUpdateObservers();
|
|
1009
|
+
|
|
1010
|
+
// No need to abort mutations
|
|
1011
|
+
// But bring it back if you want ability to "cancel"
|
|
1012
|
+
// const controller = useRef();
|
|
1013
|
+
|
|
1014
|
+
const tracker = useRef({
|
|
1015
|
+
mounted: true,
|
|
1016
|
+
timer: null as ReturnType<typeof setTimeout> | null,
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
const [mtnValues, setMtnValues] = useState({
|
|
1020
|
+
variables: null as Record<string, any> | null,
|
|
1021
|
+
saving: false,
|
|
1022
|
+
data: null,
|
|
1023
|
+
error: initialError || (null as ServerErrorObj | null),
|
|
1024
|
+
mutationCount: 0,
|
|
1025
|
+
});
|
|
1026
|
+
|
|
1027
|
+
// Mounted hook
|
|
1028
|
+
|
|
1029
|
+
useEffect(() => {
|
|
1030
|
+
return () => {
|
|
1031
|
+
tracker.current.mounted = false;
|
|
1032
|
+
if (tracker.current.timer) {
|
|
1033
|
+
clearTimeout(tracker.current.timer);
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
}, []);
|
|
1037
|
+
|
|
1038
|
+
// Mutate function for the client
|
|
1039
|
+
|
|
1040
|
+
const doMutate = async (
|
|
1041
|
+
graphqlOptions?: GraphQLRequestOptions,
|
|
1042
|
+
triedCount: number = 0,
|
|
1043
|
+
) => {
|
|
1044
|
+
// No need to abort mutations
|
|
1045
|
+
// if (controller.current) {
|
|
1046
|
+
// controller.current.abort();
|
|
1047
|
+
// }
|
|
1048
|
+
|
|
1049
|
+
// No need to abort mutations
|
|
1050
|
+
// controller.current = new AbortController();
|
|
1051
|
+
|
|
1052
|
+
setMtnValues({
|
|
1053
|
+
...mtnValues,
|
|
1054
|
+
variables: graphqlOptions?.variables || null,
|
|
1055
|
+
saving: true,
|
|
1056
|
+
});
|
|
1057
|
+
|
|
1058
|
+
const retryCount = options?.retryCount || 0;
|
|
1059
|
+
const retryDelay = getRetryDelay(triedCount);
|
|
1060
|
+
|
|
1061
|
+
const apiResult = await graphqlRequest(
|
|
1062
|
+
mutation,
|
|
1063
|
+
graphqlOptions?.variables,
|
|
1064
|
+
{
|
|
1065
|
+
cachePolicy,
|
|
1066
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
|
|
1067
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
1068
|
+
if (tracker.current.mounted) {
|
|
1069
|
+
setMtnValues({
|
|
1070
|
+
...mtnValues,
|
|
1071
|
+
mutationCount: mtnValues.mutationCount + 1,
|
|
1072
|
+
saving: false,
|
|
1073
|
+
data: data.data || null,
|
|
1074
|
+
error,
|
|
1075
|
+
});
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (data.data) {
|
|
1079
|
+
if (
|
|
1080
|
+
onCompleted &&
|
|
1081
|
+
(tracker.current.mounted || !checkMountedBeforeCallback)
|
|
1082
|
+
) {
|
|
1083
|
+
// Do separate {mounted.current} check from outside
|
|
1084
|
+
onCompleted(data.data, error, graphqlOptions?.variables);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
},
|
|
1088
|
+
onError: (error: ServerErrorObj | null) => {
|
|
1089
|
+
if (tracker.current.mounted) {
|
|
1090
|
+
setMtnValues({
|
|
1091
|
+
...mtnValues,
|
|
1092
|
+
saving: retryCount > triedCount,
|
|
1093
|
+
error,
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (
|
|
1098
|
+
onError &&
|
|
1099
|
+
retryCount <= triedCount &&
|
|
1100
|
+
(tracker.current.mounted || !checkMountedBeforeCallback)
|
|
1101
|
+
) {
|
|
1102
|
+
onError(error, graphqlOptions?.variables);
|
|
1103
|
+
}
|
|
1104
|
+
},
|
|
1105
|
+
},
|
|
1106
|
+
null, // abort controller is not needed for mutations
|
|
1107
|
+
updateObservers,
|
|
1108
|
+
);
|
|
1109
|
+
|
|
1110
|
+
if (apiResult.aborted) {
|
|
1111
|
+
return apiResult;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
1115
|
+
if (retryCount > triedCount) {
|
|
1116
|
+
await delay(retryDelay);
|
|
1117
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
1118
|
+
console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
return doMutate(graphqlOptions, triedCount + 1);
|
|
1122
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
1123
|
+
console.log(
|
|
1124
|
+
`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
return apiResult;
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
const mtnHandlers: GraphQLHandlers = {
|
|
1133
|
+
resetErrors: () => {
|
|
1134
|
+
setMtnValues({
|
|
1135
|
+
...mtnValues,
|
|
1136
|
+
error: null,
|
|
1137
|
+
});
|
|
1138
|
+
},
|
|
1139
|
+
setError: (errorObj: SimpleErrorType) => {
|
|
1140
|
+
setMtnValues({
|
|
1141
|
+
...mtnValues,
|
|
1142
|
+
error: {
|
|
1143
|
+
statusCode: 200,
|
|
1144
|
+
errorCode: 'custom_error',
|
|
1145
|
+
...errorObj,
|
|
1146
|
+
},
|
|
1147
|
+
});
|
|
1148
|
+
},
|
|
1149
|
+
refetch: () => {
|
|
1150
|
+
const lastVariables = mtnValues.variables;
|
|
1151
|
+
return doMutate(lastVariables ? { variables: lastVariables } : undefined);
|
|
1152
|
+
},
|
|
1153
|
+
setSaving: (nextSaving: boolean, resetInMS?: number) => {
|
|
1154
|
+
setMtnValues({
|
|
1155
|
+
...mtnValues,
|
|
1156
|
+
saving: nextSaving,
|
|
1157
|
+
});
|
|
1158
|
+
|
|
1159
|
+
if (nextSaving && resetInMS) {
|
|
1160
|
+
if (tracker.current.timer) {
|
|
1161
|
+
clearTimeout(tracker.current.timer);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
tracker.current.timer = setTimeout(() => {
|
|
1165
|
+
setMtnValues({
|
|
1166
|
+
...mtnValues,
|
|
1167
|
+
saving: false,
|
|
1168
|
+
});
|
|
1169
|
+
}, resetInMS);
|
|
1170
|
+
}
|
|
1171
|
+
},
|
|
1172
|
+
};
|
|
1173
|
+
|
|
1174
|
+
return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Imperatively warm the query cache for one query and variables pair.
|
|
1179
|
+
* Registers the in-flight promise in QRY_PROMISES under the same query key
|
|
1180
|
+
* useQuery() uses, so a hook mounting mid-flight awaits this request instead
|
|
1181
|
+
* of double-fetching. Prefetches are never aborted; a hook awaiting a shared
|
|
1182
|
+
* promise that resolves { aborted } would be left stuck in loading state.
|
|
1183
|
+
*/
|
|
1184
|
+
|
|
1185
|
+
export function prefetchQuery(
|
|
1186
|
+
query: any,
|
|
1187
|
+
variables?: Record<string, any> | null,
|
|
1188
|
+
options?: {
|
|
1189
|
+
authToken?: string | null;
|
|
1190
|
+
updateObservers?: UpdateObserversFn;
|
|
1191
|
+
},
|
|
1192
|
+
): Promise<any> {
|
|
1193
|
+
const queryName = query.definitions?.[0]?.name?.value;
|
|
1194
|
+
const variablesKey = makeVariablesKey(variables);
|
|
1195
|
+
const queryKey = `#${queryName}:${variablesKey}`;
|
|
1196
|
+
|
|
1197
|
+
// A complete cached result means there is nothing to warm
|
|
1198
|
+
const cachedResult = fetchCachedData(query, variablesKey);
|
|
1199
|
+
if (cachedResult) {
|
|
1200
|
+
return Promise.resolve(cachedResult);
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// A mounted hook or another prefetch already owns this request
|
|
1204
|
+
const pendingQuery = QRY_PROMISES.get(queryKey);
|
|
1205
|
+
if (pendingQuery) {
|
|
1206
|
+
return pendingQuery;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
const queryPromise = graphqlRequest(
|
|
1210
|
+
query,
|
|
1211
|
+
variables,
|
|
1212
|
+
{
|
|
1213
|
+
authToken: options?.authToken || undefined,
|
|
1214
|
+
},
|
|
1215
|
+
null,
|
|
1216
|
+
options?.updateObservers,
|
|
1217
|
+
);
|
|
1218
|
+
QRY_PROMISES.set(queryKey, queryPromise);
|
|
1219
|
+
|
|
1220
|
+
return queryPromise.finally(() => {
|
|
1221
|
+
if (QRY_PROMISES.get(queryKey) === queryPromise) {
|
|
1222
|
+
QRY_PROMISES.delete(queryKey);
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* Types; eager queries
|
|
1229
|
+
*/
|
|
1230
|
+
|
|
1231
|
+
export interface EagerQueryInstruction {
|
|
1232
|
+
// Key in EAGER_QUERY_MAP; must equal the query's GraphQL operation name
|
|
1233
|
+
queryName: string;
|
|
1234
|
+
variables?: Record<string, any> | null;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
type EagerQueriesValues = {
|
|
1238
|
+
// True while an eager batch is being fetched
|
|
1239
|
+
loading: boolean;
|
|
1240
|
+
// True once at least one eager batch has finished
|
|
1241
|
+
done: boolean;
|
|
1242
|
+
// Raw results of the last finished batch, aligned with its instructions
|
|
1243
|
+
results: any[] | null;
|
|
1244
|
+
};
|
|
1245
|
+
|
|
1246
|
+
/**
|
|
1247
|
+
* Return the global tracking key for one eager query instruction; this is the
|
|
1248
|
+
* same "#queryName:variablesKey" key the query cache and QRY_PROMISES use.
|
|
1249
|
+
*/
|
|
480
1250
|
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
1251
|
+
function makeEagerQueryKey(instruction: EagerQueryInstruction) {
|
|
1252
|
+
return `#${instruction.queryName}:${makeVariablesKey(instruction.variables)}`;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
/**
|
|
1256
|
+
* Resolve one instruction's GQL query document from the eager query registry.
|
|
1257
|
+
*/
|
|
1258
|
+
|
|
1259
|
+
function getEagerQuery(queryName: string) {
|
|
1260
|
+
const query = EAGER_QUERY_MAP[queryName];
|
|
1261
|
+
|
|
1262
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
1263
|
+
if (!query) {
|
|
1264
|
+
console.warn(
|
|
1265
|
+
`useEagerQueries() has no registered query named "${queryName}". Add it to EAGER_QUERY_MAP.`,
|
|
1266
|
+
);
|
|
1267
|
+
} else {
|
|
1268
|
+
const operationName = query.definitions?.find(
|
|
1269
|
+
(def: any) => def.kind === 'OperationDefinition',
|
|
1270
|
+
)?.name?.value;
|
|
1271
|
+
|
|
1272
|
+
if (operationName !== queryName) {
|
|
1273
|
+
console.warn(
|
|
1274
|
+
`useEagerQueries() registry key "${queryName}" does not match its GraphQL operation name "${operationName}"; ` +
|
|
1275
|
+
'the warmed cache key will never be read by useQuery().',
|
|
1276
|
+
);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
return query || null;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
/**
|
|
1285
|
+
* Imperatively warm the query cache for one registered eager query by name.
|
|
1286
|
+
* Used by hover-style eager loaders (e.g. <EagerLoad>); shares the same
|
|
1287
|
+
* registry, cache checks and global in-flight tracking as useEagerQueries().
|
|
1288
|
+
* Returns null when the query name is not registered in EAGER_QUERY_MAP.
|
|
1289
|
+
*/
|
|
1290
|
+
|
|
1291
|
+
export function prefetchEagerQuery(
|
|
1292
|
+
queryName: string,
|
|
1293
|
+
variables?: Record<string, any> | null,
|
|
1294
|
+
options?: {
|
|
1295
|
+
updateObservers?: UpdateObserversFn;
|
|
1296
|
+
},
|
|
1297
|
+
): Promise<any> | null {
|
|
1298
|
+
const query = getEagerQuery(queryName);
|
|
1299
|
+
|
|
1300
|
+
if (!query) {
|
|
1301
|
+
return null;
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
return prefetchQuery(query, variables, {
|
|
1305
|
+
updateObservers: options?.updateObservers,
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/**
|
|
1310
|
+
* Eagerly fetch many queries by name so a later useQuery() mount with the
|
|
1311
|
+
* same query and variables resolves instantly from the query cache.
|
|
1312
|
+
*
|
|
1313
|
+
* Fetch-once semantics: while {counter} is nullish or 0, one eager batch runs
|
|
1314
|
+
* when {instructions} first becomes a non-empty array, and later instruction
|
|
1315
|
+
* changes never refetch. Advancing {counter} together with new instructions
|
|
1316
|
+
* allows one more batch, but only after the previous batch finished loading
|
|
1317
|
+
* (a counter change mid-flight is rejected, not queued).
|
|
1318
|
+
*
|
|
1319
|
+
* Global single-fetch guarantee: prefetchQuery() tracks every in-flight
|
|
1320
|
+
* request in QRY_PROMISES keyed by query name + variables, so a second
|
|
1321
|
+
* component eagerly fetching the same query joins the first component's
|
|
1322
|
+
* in-flight request instead of fetching again, an already-cached result is
|
|
1323
|
+
* returned without any request, and a useQuery() hook mounting for the same
|
|
1324
|
+
* key awaits the eager promise instead of double-fetching.
|
|
1325
|
+
*
|
|
1326
|
+
* The eager requests are intentionally NOT aborted on unmount: their results
|
|
1327
|
+
* must still land in the query cache after navigation.
|
|
1328
|
+
*/
|
|
1329
|
+
|
|
1330
|
+
export function useEagerQueries(
|
|
1331
|
+
instructions?: EagerQueryInstruction[] | null,
|
|
1332
|
+
counter?: number | null,
|
|
1333
|
+
): EagerQueriesValues {
|
|
1334
|
+
const updateObservers = useUpdateObservers();
|
|
1335
|
+
const tracker = useRef({
|
|
1336
|
+
mounted: true,
|
|
1337
|
+
started: false,
|
|
1338
|
+
loading: false,
|
|
1339
|
+
counter: 0,
|
|
1340
|
+
updateObservers,
|
|
1341
|
+
});
|
|
1342
|
+
tracker.current.updateObservers = updateObservers;
|
|
1343
|
+
|
|
1344
|
+
const [eagerValues, setEagerValues] = useState<EagerQueriesValues>({
|
|
1345
|
+
loading: false,
|
|
1346
|
+
done: false,
|
|
1347
|
+
results: null,
|
|
1348
|
+
});
|
|
1349
|
+
|
|
1350
|
+
// An empty batch means the caller's source data is not ready yet, so it
|
|
1351
|
+
// must not consume the once-only fetch
|
|
1352
|
+
const instructionsKey = instructions?.length
|
|
1353
|
+
? instructions.map(makeEagerQueryKey).join('|')
|
|
1354
|
+
: '';
|
|
1355
|
+
|
|
1356
|
+
// Mounted hook; only state updates stop on unmount, never the fetches
|
|
1357
|
+
|
|
1358
|
+
useEffect(() => {
|
|
1359
|
+
tracker.current.mounted = true;
|
|
1360
|
+
|
|
1361
|
+
return () => {
|
|
1362
|
+
tracker.current.mounted = false;
|
|
1363
|
+
};
|
|
1364
|
+
}, []);
|
|
1365
|
+
|
|
1366
|
+
// Fetch when the first non-empty batch arrives, or when a later batch
|
|
1367
|
+
// arrives with an advanced counter
|
|
1368
|
+
|
|
1369
|
+
useEffect(() => {
|
|
1370
|
+
const counterValue = counter || 0;
|
|
1371
|
+
|
|
1372
|
+
if (!instructionsKey || !instructions?.length) {
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
if (tracker.current.loading) {
|
|
1377
|
+
// The previous eager batch is still in flight; reject the new batch
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
if (tracker.current.started && counterValue === tracker.current.counter) {
|
|
1382
|
+
// Without a counter change, eager fetching only ever happens once
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
tracker.current.started = true;
|
|
1387
|
+
tracker.current.loading = true;
|
|
1388
|
+
tracker.current.counter = counterValue;
|
|
1389
|
+
|
|
1390
|
+
setEagerValues((currentValues: EagerQueriesValues) => ({
|
|
1391
|
+
...currentValues,
|
|
1392
|
+
loading: true,
|
|
1393
|
+
}));
|
|
1394
|
+
|
|
1395
|
+
Promise.all(
|
|
1396
|
+
instructions.map((instruction) => {
|
|
1397
|
+
const query = getEagerQuery(instruction.queryName);
|
|
1398
|
+
|
|
1399
|
+
if (!query) {
|
|
1400
|
+
return Promise.resolve(null);
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
return prefetchQuery(query, instruction.variables, {
|
|
1404
|
+
updateObservers: tracker.current.updateObservers,
|
|
1405
|
+
});
|
|
1406
|
+
}),
|
|
1407
|
+
).then(
|
|
1408
|
+
(results) => {
|
|
1409
|
+
tracker.current.loading = false;
|
|
1410
|
+
|
|
1411
|
+
if (tracker.current.mounted) {
|
|
1412
|
+
setEagerValues({
|
|
1413
|
+
loading: false,
|
|
1414
|
+
done: true,
|
|
1415
|
+
results,
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
},
|
|
1419
|
+
() => {
|
|
1420
|
+
// prefetchQuery() resolves errors into { error } and never rejects;
|
|
1421
|
+
// this only guards against the tracker being stuck in loading state
|
|
1422
|
+
tracker.current.loading = false;
|
|
1423
|
+
|
|
1424
|
+
if (tracker.current.mounted) {
|
|
1425
|
+
setEagerValues((currentValues: EagerQueriesValues) => ({
|
|
1426
|
+
...currentValues,
|
|
1427
|
+
loading: false,
|
|
1428
|
+
}));
|
|
1429
|
+
}
|
|
1430
|
+
},
|
|
1431
|
+
);
|
|
1432
|
+
}, [instructionsKey, counter]);
|
|
1433
|
+
|
|
1434
|
+
return eagerValues;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/**
|
|
1438
|
+
* Keep the hydration snapshot immutable. Query cache changes already reach
|
|
1439
|
+
* this hook through its keyed query observer and local request state; React's
|
|
1440
|
+
* external-store consistency pass is only needed to bridge SSR hydration.
|
|
1441
|
+
*/
|
|
1442
|
+
function subscribeHydrationSafeQuerySnapshot(
|
|
1443
|
+
_onStoreChange: () => void,
|
|
1444
|
+
): () => void {
|
|
1445
|
+
return () => {};
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* Report that browser cache reads are available outside hydration.
|
|
1450
|
+
*/
|
|
1451
|
+
function getClientQuerySnapshotReady(): boolean {
|
|
1452
|
+
return true;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
/**
|
|
1456
|
+
* Keep server rendering and the first hydration render cache-free.
|
|
1457
|
+
*/
|
|
1458
|
+
function getServerQuerySnapshotReady(): boolean {
|
|
1459
|
+
return false;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/**
|
|
1463
|
+
* Read one validated query cache snapshot without exposing browser-restored
|
|
1464
|
+
* data until React has completed its hydration consistency check.
|
|
1465
|
+
*/
|
|
1466
|
+
function useHydrationSafeQueryCacheSnapshot(query: any, variablesKey: string) {
|
|
1467
|
+
const ready = useSyncExternalStore(
|
|
1468
|
+
subscribeHydrationSafeQuerySnapshot,
|
|
1469
|
+
getClientQuerySnapshotReady,
|
|
1470
|
+
getServerQuerySnapshotReady,
|
|
1471
|
+
);
|
|
1472
|
+
const data = ready ? fetchCachedData(query, variablesKey) : null;
|
|
1473
|
+
|
|
1474
|
+
return { data, ready };
|
|
641
1475
|
}
|
|
642
1476
|
|
|
643
1477
|
/**
|
|
@@ -645,307 +1479,717 @@ export function useMutation(
|
|
|
645
1479
|
*/
|
|
646
1480
|
|
|
647
1481
|
export function useQuery(
|
|
648
|
-
|
|
649
|
-
|
|
1482
|
+
query: any,
|
|
1483
|
+
options?: GraphQLQueryOptions,
|
|
650
1484
|
): GraphQLQueryResult {
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
1485
|
+
const {
|
|
1486
|
+
authToken,
|
|
1487
|
+
onCompleted,
|
|
1488
|
+
onError,
|
|
1489
|
+
openModalPopUp,
|
|
1490
|
+
variables,
|
|
1491
|
+
cacheMap,
|
|
1492
|
+
skip,
|
|
1493
|
+
eagerFragmentKeyMap,
|
|
1494
|
+
shouldAcceptResult,
|
|
1495
|
+
persistTime,
|
|
1496
|
+
} = options || {};
|
|
1497
|
+
const variablesKey = makeVariablesKey(variables);
|
|
1498
|
+
const connectedToServer = useConnectedToServerValue();
|
|
1499
|
+
const optimisticConnectedToServer = useOptimisticConnectedToServerValue();
|
|
1500
|
+
const screenIsFocused = useScreenIsFocusedValue();
|
|
1501
|
+
const updateObservers = useUpdateObservers();
|
|
1502
|
+
|
|
1503
|
+
// useQuery() assumes query is a single graphql query (and not a multi/chain)
|
|
1504
|
+
// Multiple queries can be chained using this hook,
|
|
1505
|
+
// but only the first query is used for tracking reactivity.
|
|
1506
|
+
const queryName = query.definitions?.[0]?.name?.value;
|
|
1507
|
+
const queryKey = `#${queryName}:${variablesKey}`;
|
|
1508
|
+
|
|
1509
|
+
const tracker = useRef({
|
|
1510
|
+
unique: makeQueryHookId(),
|
|
1511
|
+
abortCtrl: null as AbortController | null,
|
|
1512
|
+
activeQueryKey: null as string | null,
|
|
1513
|
+
ownQueryObserverCount: 0,
|
|
1514
|
+
reconnectedAt: null as number | null,
|
|
1515
|
+
transientRetryAttemptCount: 0,
|
|
1516
|
+
mounted: true,
|
|
1517
|
+
init: false,
|
|
1518
|
+
});
|
|
1519
|
+
const trackedUpdateObservers = useCallback(
|
|
1520
|
+
(args: UpdateDataObserverArgs) => {
|
|
1521
|
+
if (
|
|
1522
|
+
args.queryId &&
|
|
1523
|
+
args.queryId === tracker.current.activeQueryKey &&
|
|
1524
|
+
!args.forceRefetch &&
|
|
1525
|
+
!args.resetOnly
|
|
1526
|
+
) {
|
|
1527
|
+
tracker.current.ownQueryObserverCount += 1;
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
updateObservers(args);
|
|
1531
|
+
},
|
|
1532
|
+
[updateObservers],
|
|
1533
|
+
);
|
|
1534
|
+
|
|
1535
|
+
// check if p.updatedCount is needed
|
|
1536
|
+
|
|
1537
|
+
const [qryValues, setQryValues] = useState<GraphQLQueryValues>({
|
|
1538
|
+
data: null as any,
|
|
1539
|
+
variables,
|
|
1540
|
+
loading: false,
|
|
1541
|
+
error: null as ServerErrorObj | null,
|
|
1542
|
+
lastUpdatedCount: 0,
|
|
1543
|
+
lastRefreshTriggerTime: '',
|
|
1544
|
+
});
|
|
1545
|
+
|
|
1546
|
+
const qryValuesVariablesKey = makeVariablesKey(qryValues.variables);
|
|
1547
|
+
|
|
1548
|
+
const {
|
|
1549
|
+
updatedCount,
|
|
1550
|
+
forceRefetch,
|
|
1551
|
+
resetOnlyTime,
|
|
1552
|
+
qryReset: { triggerTime, refreshTime },
|
|
1553
|
+
} = useWatchQuery(
|
|
1554
|
+
query,
|
|
1555
|
+
variablesKey,
|
|
1556
|
+
qryValues.lastUpdatedCount,
|
|
1557
|
+
qryValues.loading,
|
|
1558
|
+
);
|
|
1559
|
+
const { data: cachedQuerySnapshot, ready: queryCacheSnapshotReady } =
|
|
1560
|
+
useHydrationSafeQueryCacheSnapshot(query, variablesKey);
|
|
1561
|
+
const qryValuesMatchVariables = variablesKey === qryValuesVariablesKey;
|
|
1562
|
+
const effectiveQueryData =
|
|
1563
|
+
cachedQuerySnapshot || (qryValuesMatchVariables ? qryValues.data : null);
|
|
1564
|
+
const effectiveQueryDataIsComplete = checkDataCompleteness(
|
|
1565
|
+
effectiveQueryData,
|
|
1566
|
+
query,
|
|
1567
|
+
);
|
|
1568
|
+
|
|
1569
|
+
// Query function for the client
|
|
1570
|
+
// NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
|
|
1571
|
+
|
|
1572
|
+
const doQuery = async (
|
|
1573
|
+
queryVariables?: any,
|
|
1574
|
+
triedCount: number = 0,
|
|
1575
|
+
rejectedResultCount: number = 0,
|
|
1576
|
+
silentRevalidate?: boolean,
|
|
1577
|
+
): Promise<any> => {
|
|
1578
|
+
const qryVariables = queryVariables || variables;
|
|
1579
|
+
const qryVariablesKey = makeVariablesKey(qryVariables);
|
|
1580
|
+
const qryQueryKey = `#${queryName}:${qryVariablesKey}`;
|
|
1581
|
+
const pendingQuery = QRY_PROMISES.get(qryQueryKey);
|
|
1582
|
+
|
|
1583
|
+
if (pendingQuery) {
|
|
1584
|
+
if (!silentRevalidate) {
|
|
1585
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1586
|
+
...currentValues,
|
|
1587
|
+
loading: true,
|
|
1588
|
+
}));
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
return pendingQuery.then((apiResult) => {
|
|
1592
|
+
if (apiResult?.aborted) {
|
|
1593
|
+
if (!tracker.current.mounted) {
|
|
1594
|
+
return apiResult;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// Retire the aborted owner's global slots before retrying. A warm
|
|
1598
|
+
// cached result is complete, so no later state transition would
|
|
1599
|
+
// otherwise retrigger this silent stale-cache revalidation.
|
|
1600
|
+
if (QRY_PROMISES.get(qryQueryKey) === pendingQuery) {
|
|
1601
|
+
QRY_PROMISES.delete(qryQueryKey);
|
|
1602
|
+
QRY_TRACKER.delete(qryQueryKey);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1606
|
+
...currentValues,
|
|
1607
|
+
loading: false,
|
|
1608
|
+
}));
|
|
1609
|
+
|
|
1610
|
+
return doQuery(
|
|
1611
|
+
queryVariables,
|
|
1612
|
+
triedCount,
|
|
1613
|
+
rejectedResultCount,
|
|
1614
|
+
silentRevalidate,
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
if (!tracker.current.mounted) {
|
|
1619
|
+
return apiResult;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
const cachedResult = fetchCachedData(query, qryVariablesKey);
|
|
1623
|
+
const data =
|
|
1624
|
+
cachedResult || getQueryDataFromAPIResult(queryName, apiResult);
|
|
1625
|
+
|
|
1626
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1627
|
+
...currentValues,
|
|
1628
|
+
variables: qryVariables,
|
|
1629
|
+
data: data || currentValues.data,
|
|
1630
|
+
loading: false,
|
|
1631
|
+
error: apiResult?.error || null,
|
|
1632
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(
|
|
1633
|
+
currentValues.lastUpdatedCount,
|
|
1634
|
+
updatedCount,
|
|
1635
|
+
0,
|
|
1636
|
+
),
|
|
1637
|
+
lastRefreshTriggerTime:
|
|
1638
|
+
triggerTime || currentValues.lastRefreshTriggerTime,
|
|
1639
|
+
}));
|
|
1640
|
+
|
|
1641
|
+
return apiResult;
|
|
1642
|
+
});
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
const currentHookId = QRY_TRACKER.get(qryQueryKey);
|
|
1646
|
+
if (!currentHookId) {
|
|
1647
|
+
QRY_TRACKER.set(qryQueryKey, tracker.current.unique);
|
|
1648
|
+
} else if (currentHookId) {
|
|
1649
|
+
// This query is being fetched already, so do nothing
|
|
1650
|
+
// This can happen in 2 ways;
|
|
1651
|
+
// 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
|
|
1652
|
+
// 2. useWatchQuery() caused 2 hooks with same query to be called at once
|
|
1653
|
+
return { loading: true, skipped: true };
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
if (tracker.current.abortCtrl && qryValues.loading) {
|
|
1657
|
+
// doLog(query, 'Query component [$0] is being aborted before being refetched.');
|
|
1658
|
+
// console.log('ABORT:', queryKey, tracker.current.unique);
|
|
1659
|
+
tracker.current.abortCtrl.abort({
|
|
1660
|
+
name: 'AbortError',
|
|
1661
|
+
message: `Hook for ${qryQueryKey} has aborted because the [query refetched before the previous one ended].`,
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
tracker.current.abortCtrl = new AbortController();
|
|
1666
|
+
tracker.current.activeQueryKey = qryQueryKey;
|
|
1667
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1668
|
+
|
|
1669
|
+
if (!silentRevalidate) {
|
|
1670
|
+
// Background stale-while-revalidate keeps loading=false so consumers
|
|
1671
|
+
// keep rendering the served cached data without spinners
|
|
1672
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1673
|
+
...currentValues,
|
|
1674
|
+
loading: true,
|
|
1675
|
+
}));
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
const retryCount = options?.retryCount || 0;
|
|
1679
|
+
const retryDelay = getRetryDelay(triedCount);
|
|
1680
|
+
// const qryName = query.definitions?.[0]?.name?.value;
|
|
1681
|
+
|
|
1682
|
+
// doLog(query, 'Query component [$0] is being refetched.');
|
|
1683
|
+
|
|
1684
|
+
const queryPromise = graphqlRequest(
|
|
1685
|
+
query,
|
|
1686
|
+
qryVariables,
|
|
1687
|
+
{
|
|
1688
|
+
authToken: authToken || undefined,
|
|
1689
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
|
|
1690
|
+
cacheMap,
|
|
1691
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
1692
|
+
if (data.data) {
|
|
1693
|
+
const ownQueryObserverCount = tracker.current.ownQueryObserverCount;
|
|
1694
|
+
const completedData =
|
|
1695
|
+
fetchCachedData(query, qryVariablesKey) || data.data;
|
|
1696
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1697
|
+
|
|
1698
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1699
|
+
...currentValues,
|
|
1700
|
+
variables: qryVariables,
|
|
1701
|
+
// Prime and retain the validated normalized snapshot while the
|
|
1702
|
+
// network result is already off the navigation-critical path.
|
|
1703
|
+
data: completedData,
|
|
1704
|
+
loading: false,
|
|
1705
|
+
error,
|
|
1706
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(
|
|
1707
|
+
currentValues.lastUpdatedCount,
|
|
1708
|
+
updatedCount,
|
|
1709
|
+
ownQueryObserverCount,
|
|
1710
|
+
),
|
|
1711
|
+
lastRefreshTriggerTime:
|
|
1712
|
+
triggerTime || currentValues.lastRefreshTriggerTime,
|
|
1713
|
+
}));
|
|
1714
|
+
|
|
1715
|
+
if (onCompleted) {
|
|
1716
|
+
onCompleted(data.data, error, qryVariables);
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
removeStaleCache();
|
|
1720
|
+
tracker.current.reconnectedAt = Date.now();
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
tracker.current.activeQueryKey = null;
|
|
1724
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1725
|
+
},
|
|
1726
|
+
onError: (error: ServerErrorObj | null) => {
|
|
1727
|
+
tracker.current.activeQueryKey = null;
|
|
1728
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1729
|
+
|
|
1730
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1731
|
+
...currentValues,
|
|
1732
|
+
variables: qryVariables,
|
|
1733
|
+
loading: retryCount > triedCount,
|
|
1734
|
+
error,
|
|
1735
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(
|
|
1736
|
+
currentValues.lastUpdatedCount,
|
|
1737
|
+
updatedCount,
|
|
1738
|
+
0,
|
|
1739
|
+
),
|
|
1740
|
+
lastRefreshTriggerTime:
|
|
1741
|
+
triggerTime || currentValues.lastRefreshTriggerTime,
|
|
1742
|
+
}));
|
|
1743
|
+
|
|
1744
|
+
if (onError && retryCount <= triedCount) {
|
|
1745
|
+
onError(error, qryVariables);
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1749
|
+
},
|
|
1750
|
+
shouldAcceptResult,
|
|
1751
|
+
},
|
|
1752
|
+
tracker.current.abortCtrl.signal,
|
|
1753
|
+
trackedUpdateObservers,
|
|
1754
|
+
);
|
|
1755
|
+
QRY_PROMISES.set(qryQueryKey, queryPromise);
|
|
1756
|
+
|
|
1757
|
+
let apiResult: any;
|
|
1758
|
+
try {
|
|
1759
|
+
apiResult = await queryPromise;
|
|
1760
|
+
} finally {
|
|
1761
|
+
if (QRY_PROMISES.get(qryQueryKey) === queryPromise) {
|
|
1762
|
+
QRY_PROMISES.delete(qryQueryKey);
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
if (apiResult.aborted) {
|
|
1767
|
+
tracker.current.activeQueryKey = null;
|
|
1768
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1769
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1770
|
+
return apiResult;
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
if (apiResult.__clientResultRejected) {
|
|
1774
|
+
tracker.current.activeQueryKey = null;
|
|
1775
|
+
tracker.current.ownQueryObserverCount = 0;
|
|
1776
|
+
unsetQueryTracker(qryQueryKey, tracker.current.unique);
|
|
1777
|
+
const rejectedResultRetryCount = Math.min(
|
|
1778
|
+
2,
|
|
1779
|
+
Math.max(0, Math.floor(options?.rejectedResultRetryCount || 0)),
|
|
1780
|
+
);
|
|
1781
|
+
if (rejectedResultCount < rejectedResultRetryCount) {
|
|
1782
|
+
tracker.current.abortCtrl = null;
|
|
1783
|
+
return doQuery(queryVariables, triedCount, rejectedResultCount + 1);
|
|
1784
|
+
}
|
|
1785
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1786
|
+
...currentValues,
|
|
1787
|
+
loading: false,
|
|
1788
|
+
lastUpdatedCount: getNextQueryLastUpdatedCount(
|
|
1789
|
+
currentValues.lastUpdatedCount,
|
|
1790
|
+
updatedCount,
|
|
1791
|
+
0,
|
|
1792
|
+
),
|
|
1793
|
+
}));
|
|
1794
|
+
return apiResult;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
1798
|
+
if (retryCount > triedCount) {
|
|
1799
|
+
await delay(retryDelay);
|
|
1800
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
1801
|
+
console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
return doQuery(queryVariables, triedCount + 1);
|
|
1805
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
1806
|
+
console.log(
|
|
1807
|
+
`query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
1808
|
+
);
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
return apiResult;
|
|
1813
|
+
};
|
|
1814
|
+
|
|
1815
|
+
/*
|
|
1816
|
+
* Reassess hydration-safe warm snapshots when their activation inputs
|
|
1817
|
+
* change. The query-keyed promise registry deduplicates overlapping loads.
|
|
1818
|
+
*/
|
|
1819
|
+
useEffect(() => {
|
|
1820
|
+
if (
|
|
1821
|
+
!queryCacheSnapshotReady ||
|
|
1822
|
+
!cachedQuerySnapshot ||
|
|
1823
|
+
skip ||
|
|
1824
|
+
!optimisticConnectedToServer
|
|
1825
|
+
) {
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
if (forceRefetch || resetOnlyTime || triggerTime) {
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
if (
|
|
1834
|
+
updatedCount !== qryValues.lastUpdatedCount ||
|
|
1835
|
+
variablesKey !== qryValuesVariablesKey
|
|
1836
|
+
) {
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
tracker.current.reconnectedAt =
|
|
1841
|
+
getQueryLastFetchedAt(queryKey) || Date.now();
|
|
1842
|
+
|
|
1843
|
+
if (queryDataIsStale(queryName, queryKey, persistTime)) {
|
|
1844
|
+
void doQuery(undefined, 0, 0, true);
|
|
1845
|
+
}
|
|
1846
|
+
}, [
|
|
1847
|
+
cachedQuerySnapshot,
|
|
1848
|
+
forceRefetch,
|
|
1849
|
+
optimisticConnectedToServer,
|
|
1850
|
+
queryCacheSnapshotReady,
|
|
1851
|
+
queryKey,
|
|
1852
|
+
qryValues.lastUpdatedCount,
|
|
1853
|
+
qryValuesVariablesKey,
|
|
1854
|
+
resetOnlyTime,
|
|
1855
|
+
skip,
|
|
1856
|
+
triggerTime,
|
|
1857
|
+
updatedCount,
|
|
1858
|
+
variablesKey,
|
|
1859
|
+
]);
|
|
1860
|
+
|
|
1861
|
+
// Mount & unmount
|
|
1862
|
+
|
|
1863
|
+
useEffect(() => {
|
|
1864
|
+
tracker.current.mounted = true;
|
|
1865
|
+
|
|
1866
|
+
return () => {
|
|
1867
|
+
tracker.current.mounted = false;
|
|
1868
|
+
unsetQueryTracker(queryKey, tracker.current.unique);
|
|
1869
|
+
};
|
|
1870
|
+
}, [queryKey]);
|
|
1871
|
+
|
|
1872
|
+
useEffect(() => {
|
|
1873
|
+
return () => {
|
|
1874
|
+
if (tracker.current.abortCtrl) {
|
|
1875
|
+
// console.log('UMOUNTED:', queryKey, tracker.current.unique);
|
|
1876
|
+
tracker.current.abortCtrl.abort({
|
|
1877
|
+
name: 'AbortError',
|
|
1878
|
+
message: `Hook for ${queryKey} has aborted because [the component unmounted].`,
|
|
1879
|
+
});
|
|
1880
|
+
}
|
|
1881
|
+
};
|
|
1882
|
+
}, []);
|
|
1883
|
+
|
|
1884
|
+
// Refetch when variables, skip status or query observer changes
|
|
1885
|
+
|
|
1886
|
+
// const isTest = queryName === 'logEntries';
|
|
1887
|
+
|
|
1888
|
+
useEffect(() => {
|
|
1889
|
+
// isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
|
|
1890
|
+
|
|
1891
|
+
if (
|
|
1892
|
+
queryCacheSnapshotReady &&
|
|
1893
|
+
!skip &&
|
|
1894
|
+
((triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
|
|
1895
|
+
updatedCount !== qryValues.lastUpdatedCount ||
|
|
1896
|
+
variablesKey !== qryValuesVariablesKey ||
|
|
1897
|
+
(!qryValues.error && !effectiveQueryDataIsComplete))
|
|
1898
|
+
) {
|
|
1899
|
+
const currentDataMatchesVariables =
|
|
1900
|
+
effectiveQueryDataIsComplete &&
|
|
1901
|
+
(!!cachedQuerySnapshot || variablesKey === qryValuesVariablesKey);
|
|
1902
|
+
const canAcknowledgeCurrentData =
|
|
1903
|
+
currentDataMatchesVariables &&
|
|
1904
|
+
!forceRefetch &&
|
|
1905
|
+
!resetOnlyTime &&
|
|
1906
|
+
!triggerTime;
|
|
1907
|
+
|
|
1908
|
+
if (canAcknowledgeCurrentData) {
|
|
1909
|
+
setQryValues((currentValues: GraphQLQueryValues) => ({
|
|
1910
|
+
...currentValues,
|
|
1911
|
+
variables,
|
|
1912
|
+
data: effectiveQueryData,
|
|
1913
|
+
lastUpdatedCount: updatedCount || 0,
|
|
1914
|
+
}));
|
|
1915
|
+
return;
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
const cachedResult =
|
|
1919
|
+
cachedQuerySnapshot ||
|
|
1920
|
+
fetchCachedData(query, variablesKey, updateObservers);
|
|
1921
|
+
if (cachedResult) {
|
|
1922
|
+
setQryValues({
|
|
1923
|
+
...qryValues,
|
|
1924
|
+
variables,
|
|
1925
|
+
data: cachedResult,
|
|
1926
|
+
error: null,
|
|
1927
|
+
loading: false, // IMPORTANT: must be false here
|
|
1928
|
+
lastRefreshTriggerTime: triggerTime,
|
|
1929
|
+
lastUpdatedCount: updatedCount || 0,
|
|
1930
|
+
});
|
|
1931
|
+
|
|
1932
|
+
// Anchor the focus/reconnect expiry logic to when this data was
|
|
1933
|
+
// actually fetched (hydrated snapshots would otherwise never expire)
|
|
1934
|
+
const lastFetchedAt = getQueryLastFetchedAt(queryKey);
|
|
1935
|
+
if (!tracker.current.reconnectedAt) {
|
|
1936
|
+
tracker.current.reconnectedAt = lastFetchedAt || Date.now();
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
if (forceRefetch && !qryValues.loading) {
|
|
1940
|
+
// doLog(query, 'forceRefetchhing query at: $0|' + variablesKey + skip + updatedCount);
|
|
1941
|
+
doQuery();
|
|
1942
|
+
// isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
|
|
1943
|
+
// console.log('::', variablesKey, skip, updatedCount);
|
|
1944
|
+
} else if (
|
|
1945
|
+
!qryValues.loading &&
|
|
1946
|
+
connectedToServer &&
|
|
1947
|
+
queryDataIsStale(queryName, queryKey, persistTime)
|
|
1948
|
+
) {
|
|
1949
|
+
// Cached data is served above; refresh it silently in the
|
|
1950
|
+
// background (stale-while-revalidate)
|
|
1951
|
+
doQuery(undefined, 0, 0, true);
|
|
1952
|
+
}
|
|
1953
|
+
} else if (!qryValues.loading) {
|
|
1954
|
+
// isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
|
|
1955
|
+
// doLog(query, '!qryValues.loading, doing query at: $0|' + variablesKey + skip + updatedCount);
|
|
1956
|
+
// doLog(query, '1: ' + (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime));
|
|
1957
|
+
// doLog(query, '2: ' + (updatedCount !== qryValues.lastUpdatedCount));
|
|
1958
|
+
// doLog(query, '3: ' + (variablesKey !== qryValuesVariablesKey));
|
|
1959
|
+
// doLog(query, '4: ' + (!qryValues.error && !checkDataCompleteness(qryValues.data, query)));
|
|
1960
|
+
// doLog(query, 'variablesKey 1: ' + variablesKey);
|
|
1961
|
+
// doLog(query, 'variablesKey 2: ' + qryValuesVariablesKey);
|
|
1962
|
+
|
|
1963
|
+
doQuery();
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
}, [
|
|
1967
|
+
cachedQuerySnapshot,
|
|
1968
|
+
effectiveQueryDataIsComplete,
|
|
1969
|
+
queryCacheSnapshotReady,
|
|
1970
|
+
variablesKey,
|
|
1971
|
+
qryValuesVariablesKey,
|
|
1972
|
+
qryValues.loading,
|
|
1973
|
+
skip,
|
|
1974
|
+
updatedCount,
|
|
1975
|
+
triggerTime,
|
|
1976
|
+
]);
|
|
1977
|
+
|
|
1978
|
+
// Refetch when the app reconnects and has no data
|
|
1979
|
+
|
|
1980
|
+
const withoutData = effectiveQueryData === null;
|
|
1981
|
+
const reconnectedWithoutData =
|
|
1982
|
+
queryCacheSnapshotReady &&
|
|
1983
|
+
!skip &&
|
|
1984
|
+
!qryValues.error &&
|
|
1985
|
+
withoutData &&
|
|
1986
|
+
!qryValues.loading &&
|
|
1987
|
+
connectedToServer;
|
|
1988
|
+
|
|
1989
|
+
useEffect(() => {
|
|
1990
|
+
if (
|
|
1991
|
+
queryCacheSnapshotReady &&
|
|
1992
|
+
connectedToServer &&
|
|
1993
|
+
screenIsFocused &&
|
|
1994
|
+
!skip &&
|
|
1995
|
+
!qryValues.error
|
|
1996
|
+
) {
|
|
1997
|
+
const now = Date.now();
|
|
1998
|
+
|
|
1999
|
+
let timeDiff: number, timeThresh: number;
|
|
2000
|
+
if (reconnectedWithoutData) {
|
|
2001
|
+
timeDiff = tracker.current.reconnectedAt
|
|
2002
|
+
? now - tracker.current.reconnectedAt
|
|
2003
|
+
: Infinity;
|
|
2004
|
+
timeThresh = 5000;
|
|
2005
|
+
} else {
|
|
2006
|
+
timeDiff = tracker.current.reconnectedAt
|
|
2007
|
+
? now - tracker.current.reconnectedAt
|
|
2008
|
+
: -Infinity;
|
|
2009
|
+
timeThresh =
|
|
2010
|
+
QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// console.log('>>', queryName, timeDiff, timeThresh, timeDiff > timeThresh);
|
|
2014
|
+
|
|
2015
|
+
if (tracker.current.init && timeDiff > timeThresh) {
|
|
2016
|
+
// console.log('query again:', queryName, timeDiff);
|
|
2017
|
+
// doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
|
|
2018
|
+
tracker.current.reconnectedAt = now;
|
|
2019
|
+
doQuery();
|
|
2020
|
+
} else {
|
|
2021
|
+
tracker.current.init = true;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
}, [queryCacheSnapshotReady, reconnectedWithoutData, screenIsFocused]);
|
|
2025
|
+
|
|
2026
|
+
const transientError = isTransientServerError(qryValues.error);
|
|
2027
|
+
|
|
2028
|
+
/*
|
|
2029
|
+
* Keep the last successful result mounted while a deployment or temporary
|
|
2030
|
+
* transport outage is retried after the websocket reports connectivity.
|
|
2031
|
+
*/
|
|
2032
|
+
useEffect(() => {
|
|
2033
|
+
if (!options?.retryTransientErrors || !transientError) {
|
|
2034
|
+
tracker.current.transientRetryAttemptCount = 0;
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
if (skip || qryValues.loading || !connectedToServer || !screenIsFocused) {
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
|
|
2041
|
+
const retryDelay = getTransientRetryDelay(
|
|
2042
|
+
tracker.current.transientRetryAttemptCount,
|
|
2043
|
+
);
|
|
2044
|
+
const retryAuthToken = getAuthToken();
|
|
2045
|
+
const timeoutId = globalThis.setTimeout(() => {
|
|
2046
|
+
if (!authContextMatchesRetryToken(retryAuthToken, getAuthToken())) {
|
|
2047
|
+
tracker.current.transientRetryAttemptCount = 0;
|
|
2048
|
+
return;
|
|
2049
|
+
}
|
|
2050
|
+
tracker.current.transientRetryAttemptCount += 1;
|
|
2051
|
+
void doQuery();
|
|
2052
|
+
}, retryDelay);
|
|
2053
|
+
|
|
2054
|
+
return () => {
|
|
2055
|
+
globalThis.clearTimeout(timeoutId);
|
|
2056
|
+
};
|
|
2057
|
+
}, [
|
|
2058
|
+
connectedToServer,
|
|
2059
|
+
qryValues.loading,
|
|
2060
|
+
screenIsFocused,
|
|
2061
|
+
skip,
|
|
2062
|
+
transientError,
|
|
2063
|
+
variablesKey,
|
|
2064
|
+
]);
|
|
2065
|
+
|
|
2066
|
+
/*
|
|
2067
|
+
* Keep imperative refreshes behind the same skip boundary as effect-driven
|
|
2068
|
+
* loads so stale observers cannot send temporarily null required variables.
|
|
2069
|
+
*/
|
|
2070
|
+
const queryRuntimeRef = useRef({ doQuery, skip });
|
|
2071
|
+
|
|
2072
|
+
/*
|
|
2073
|
+
* Publish only committed query variables to stable imperative callbacks.
|
|
2074
|
+
*/
|
|
2075
|
+
useLayoutEffect(() => {
|
|
2076
|
+
queryRuntimeRef.current = { doQuery, skip };
|
|
2077
|
+
});
|
|
2078
|
+
|
|
2079
|
+
/*
|
|
2080
|
+
* Refetch with the latest render's query runtime while keeping the public
|
|
2081
|
+
* callback identity stable for memoized consumers.
|
|
2082
|
+
*/
|
|
2083
|
+
const refetch = useCallback(() => {
|
|
2084
|
+
const queryRuntime = queryRuntimeRef.current;
|
|
2085
|
+
return queryRuntime.skip
|
|
2086
|
+
? Promise.resolve({ skipped: true })
|
|
2087
|
+
: queryRuntime.doQuery();
|
|
2088
|
+
}, []);
|
|
2089
|
+
|
|
2090
|
+
/*
|
|
2091
|
+
* Fetch another variables page through the latest query runtime while
|
|
2092
|
+
* retaining a stable callback identity.
|
|
2093
|
+
*/
|
|
2094
|
+
const fetchMore = useCallback(
|
|
2095
|
+
async (obj: GraphQLRequestOptions): Promise<any> => {
|
|
2096
|
+
const queryRuntime = queryRuntimeRef.current;
|
|
2097
|
+
if (queryRuntime.skip) {
|
|
2098
|
+
return { skipped: true };
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
const result = await queryRuntime.doQuery(obj?.variables);
|
|
2102
|
+
|
|
2103
|
+
if (result.error) {
|
|
2104
|
+
return {
|
|
2105
|
+
...result,
|
|
2106
|
+
error: normalizeServerError(result.error),
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
return result;
|
|
2111
|
+
},
|
|
2112
|
+
[],
|
|
2113
|
+
);
|
|
2114
|
+
|
|
2115
|
+
const queryData = useMemo(() => {
|
|
2116
|
+
if (!queryCacheSnapshotReady) {
|
|
2117
|
+
return {};
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
return loadDataFromCache(
|
|
2121
|
+
effectiveQueryData,
|
|
2122
|
+
query,
|
|
2123
|
+
variablesKey,
|
|
2124
|
+
cacheMap,
|
|
2125
|
+
eagerFragmentKeyMap,
|
|
2126
|
+
false,
|
|
2127
|
+
);
|
|
2128
|
+
}, [
|
|
2129
|
+
cacheMap,
|
|
2130
|
+
eagerFragmentKeyMap,
|
|
2131
|
+
effectiveQueryData,
|
|
2132
|
+
query,
|
|
2133
|
+
queryCacheSnapshotReady,
|
|
2134
|
+
updatedCount,
|
|
2135
|
+
variablesKey,
|
|
2136
|
+
]);
|
|
2137
|
+
|
|
2138
|
+
const resultData = queryData[queryName];
|
|
2139
|
+
const queryOutputRef = useRef<GraphQLQueryOutput>({
|
|
2140
|
+
queryKey,
|
|
2141
|
+
refreshTime,
|
|
2142
|
+
data: null,
|
|
2143
|
+
});
|
|
2144
|
+
const hasFreshData = resultData !== undefined;
|
|
2145
|
+
|
|
2146
|
+
/*
|
|
2147
|
+
* Retain the last committed complete output for uncached variable changes.
|
|
2148
|
+
*/
|
|
2149
|
+
useEffect(() => {
|
|
2150
|
+
if (!hasFreshData) {
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
queryOutputRef.current = {
|
|
2155
|
+
queryKey,
|
|
2156
|
+
refreshTime,
|
|
2157
|
+
data: queryData,
|
|
2158
|
+
};
|
|
2159
|
+
}, [hasFreshData, queryData, queryKey, refreshTime]);
|
|
2160
|
+
|
|
2161
|
+
// A null result still counts as data; only undefined means "not fetched yet".
|
|
2162
|
+
const queryOutput = queryOutputRef.current;
|
|
2163
|
+
|
|
2164
|
+
return {
|
|
2165
|
+
...qryValues,
|
|
2166
|
+
queryName,
|
|
2167
|
+
queryKey: hasFreshData ? queryKey : queryOutput.queryKey,
|
|
2168
|
+
data: hasFreshData ? queryData : queryOutput.data || queryData,
|
|
2169
|
+
refreshTime: hasFreshData ? refreshTime : queryOutput.refreshTime,
|
|
2170
|
+
resetOnlyTime,
|
|
2171
|
+
variablesKey,
|
|
2172
|
+
refetch,
|
|
2173
|
+
fetchMore,
|
|
2174
|
+
updatedCount,
|
|
2175
|
+
updateObservers,
|
|
2176
|
+
connectedToServer,
|
|
2177
|
+
recovering: Boolean(options?.retryTransientErrors && transientError),
|
|
2178
|
+
screenIsFocused,
|
|
2179
|
+
};
|
|
951
2180
|
}
|
|
2181
|
+
|
|
2182
|
+
/**
|
|
2183
|
+
* Helper: For development purposes; do not remove.
|
|
2184
|
+
*/
|
|
2185
|
+
|
|
2186
|
+
// function getQueryName(query: any) {
|
|
2187
|
+
// return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
|
|
2188
|
+
// }
|
|
2189
|
+
|
|
2190
|
+
// function doLog(query: any, logStr: string) {
|
|
2191
|
+
// const queryName = getQueryName(query);
|
|
2192
|
+
// if (queryName === 'dataTableRowsForSheetRegions') {
|
|
2193
|
+
// console.log(logStr.replace(/\$0/gi, queryName));
|
|
2194
|
+
// }
|
|
2195
|
+
// }
|