@jsb188/graphql 1.0.2 → 1.0.4
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 +1 -0
- package/cache/index.ts +23 -32
- package/client/hooks.ts +775 -0
- package/client/index.ts +2 -0
- package/client/request.ts +194 -0
- package/gql/queries/aiChatQueries.ts +21 -9
- package/package.json +11 -6
- package/sse.ts +139 -0
- package/{cache/utils.ts → utils.ts} +28 -0
- package/main.ts +0 -2
package/cache/config.ts
CHANGED
package/cache/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { cloneArrayLike } from '@jsb188/app/utils/object';
|
|
1
2
|
import type { UpdateObserversFn } from '../types.d';
|
|
2
3
|
import { RULES, PARTIALS_MAP } from './config';
|
|
3
4
|
|
|
@@ -61,28 +62,13 @@ export function mergeNestedObjects(obj1: any, obj2: any) {
|
|
|
61
62
|
return newObj;
|
|
62
63
|
}
|
|
63
64
|
|
|
64
|
-
/**
|
|
65
|
-
* Check if Object is array-like, then convert to plain Object.
|
|
66
|
-
* NOTE: This happens a lot when using JS Map()
|
|
67
|
-
* NOTE: This assumes that the keys are ordered numbers
|
|
68
|
-
* NOTE: This function always clones the object.
|
|
69
|
-
*/
|
|
70
|
-
|
|
71
|
-
export function cloneArrayLike(obj: any) {
|
|
72
|
-
if (
|
|
73
|
-
!Array.isArray(obj) &&
|
|
74
|
-
Object.keys(obj).every((key, i) => key === i.toString())
|
|
75
|
-
) {
|
|
76
|
-
return Object.values(obj);
|
|
77
|
-
}
|
|
78
|
-
return { ...obj };
|
|
79
|
-
}
|
|
80
|
-
|
|
81
65
|
/**
|
|
82
66
|
* Get a single string to represent all variables for a query
|
|
83
67
|
* NOTE: This isn't perfect because variables could have extra or unnnecessary keys/values
|
|
84
68
|
* The correct way to do this would be to compare it against the query {variableDefinitions}
|
|
85
69
|
* But this will work as long as each variables object is used consistently to match the used query.
|
|
70
|
+
*
|
|
71
|
+
* NOTE: Same logic is used in SSE [publish.ts]
|
|
86
72
|
*/
|
|
87
73
|
|
|
88
74
|
export function makeVariablesKey(variables?: any) {
|
|
@@ -328,6 +314,9 @@ function saveQueryToMemory(
|
|
|
328
314
|
return;
|
|
329
315
|
}
|
|
330
316
|
|
|
317
|
+
// IMPORTANT NOTE:
|
|
318
|
+
// Queries are never cached unless they are manually set in [./config.ts]
|
|
319
|
+
|
|
331
320
|
const data = requestData[qryName];
|
|
332
321
|
const queryId = `#${qryName}:${variablesKey}`;
|
|
333
322
|
const selections = selection?.selectionSet?.selections;
|
|
@@ -362,8 +351,7 @@ function saveQueryToMemory(
|
|
|
362
351
|
// cacheMap[key](data[key], cacheObj[key], sel, variables);
|
|
363
352
|
if (saveQueryToCache) {
|
|
364
353
|
const customCacheData = cacheMap(data, cacheData, selections, variables);
|
|
365
|
-
// console.log('--->', queryId);
|
|
366
|
-
|
|
354
|
+
// console.log('1--->', queryId);
|
|
367
355
|
QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
|
|
368
356
|
|
|
369
357
|
if (updateObservers) {
|
|
@@ -374,7 +362,8 @@ function saveQueryToMemory(
|
|
|
374
362
|
}
|
|
375
363
|
} else {
|
|
376
364
|
if (saveQueryToCache) {
|
|
377
|
-
// console.log('--->', queryId);
|
|
365
|
+
// console.log('2--->', queryId);
|
|
366
|
+
// console.log('2--->', cacheData);
|
|
378
367
|
QUERIES.set(queryId, cacheData);
|
|
379
368
|
}
|
|
380
369
|
|
|
@@ -448,10 +437,11 @@ export function appendFragmentToCache(cacheData: any) {
|
|
|
448
437
|
let cacheIsValid = true;
|
|
449
438
|
|
|
450
439
|
if (newObj[key].__list) {
|
|
451
|
-
cachedObj = newObj[key].data.map((di) => {
|
|
440
|
+
cachedObj = newObj[key].data.map((di: any[]) => {
|
|
452
441
|
let item = {};
|
|
453
442
|
di.forEach((d) => {
|
|
454
443
|
if (Array.isArray(d)) {
|
|
444
|
+
// @ts-expect-error
|
|
455
445
|
item[d[0]] = d[1];
|
|
456
446
|
} else if (typeof d === 'string') {
|
|
457
447
|
const frgIndex = d.indexOf(':');
|
|
@@ -488,8 +478,9 @@ export function appendFragmentToCache(cacheData: any) {
|
|
|
488
478
|
return item;
|
|
489
479
|
});
|
|
490
480
|
} else {
|
|
491
|
-
newObj[key].data.forEach((d) => {
|
|
481
|
+
newObj[key].data.forEach((d: any) => {
|
|
492
482
|
if (Array.isArray(d)) {
|
|
483
|
+
// @ts-expect-error
|
|
493
484
|
cachedObj[d[0]] = d[1];
|
|
494
485
|
} else if (typeof d === 'string') {
|
|
495
486
|
const frgIndex = d.indexOf(':');
|
|
@@ -562,7 +553,7 @@ export function loadDataFromCache(
|
|
|
562
553
|
|
|
563
554
|
for (const def of definitions) {
|
|
564
555
|
if (def.kind === 'OperationDefinition') {
|
|
565
|
-
def?.selectionSet?.selections.forEach((selection) => {
|
|
556
|
+
def?.selectionSet?.selections.forEach((selection: any) => {
|
|
566
557
|
const qryName = selection.name?.value;
|
|
567
558
|
if (!data[qryName]) {
|
|
568
559
|
const cacheKey = `#${qryName}:${variablesKey}`;
|
|
@@ -758,13 +749,13 @@ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObserv
|
|
|
758
749
|
*/
|
|
759
750
|
|
|
760
751
|
export function updateFragment(
|
|
761
|
-
|
|
762
|
-
update: any | ((cache: any) =>
|
|
752
|
+
updateFragmentKey: string,
|
|
753
|
+
update: any | ((cache: any) => any),
|
|
763
754
|
replaceId?: string | null,
|
|
764
755
|
doNotTriggerObserver?: boolean,
|
|
765
756
|
updateObservers?: UpdateObserversFn,
|
|
766
757
|
) {
|
|
767
|
-
const cache = loadFragment(
|
|
758
|
+
const cache = loadFragment(updateFragmentKey);
|
|
768
759
|
|
|
769
760
|
if (cache && update) {
|
|
770
761
|
let updateObj;
|
|
@@ -776,9 +767,9 @@ export function updateFragment(
|
|
|
776
767
|
|
|
777
768
|
const updatedObj = { ...cache, ...updateObj };
|
|
778
769
|
|
|
779
|
-
FRAGMENTS.set(
|
|
770
|
+
FRAGMENTS.set(updateFragmentKey, updatedObj);
|
|
780
771
|
|
|
781
|
-
if (replaceId && replaceId !==
|
|
772
|
+
if (replaceId && replaceId !== updateFragmentKey) {
|
|
782
773
|
FRAGMENTS.set(replaceId, updatedObj);
|
|
783
774
|
|
|
784
775
|
// Must be deleted later, for the observer to work properly
|
|
@@ -787,15 +778,15 @@ export function updateFragment(
|
|
|
787
778
|
|
|
788
779
|
if (!doNotTriggerObserver && updateObservers) {
|
|
789
780
|
updateObservers({
|
|
790
|
-
fragmentIds: [
|
|
781
|
+
fragmentIds: [updateFragmentKey],
|
|
791
782
|
});
|
|
792
783
|
|
|
793
784
|
// FRAGMENT_OBSERVER.value = {
|
|
794
785
|
// count: FRAGMENT_OBSERVER.value.count + 1,
|
|
795
|
-
// list: [
|
|
786
|
+
// list: [updateFragmentKey],
|
|
796
787
|
// };
|
|
797
788
|
}
|
|
798
|
-
return
|
|
789
|
+
return updateFragmentKey || null;
|
|
799
790
|
}
|
|
800
791
|
return null;
|
|
801
792
|
}
|
|
@@ -806,7 +797,7 @@ export function updateFragment(
|
|
|
806
797
|
|
|
807
798
|
export function updateQuery(
|
|
808
799
|
queryId: string,
|
|
809
|
-
update: any | ((cache: any) =>
|
|
800
|
+
update: any | ((cache: any) => any),
|
|
810
801
|
doNotTriggerObserver?: boolean,
|
|
811
802
|
updateObservers?: UpdateObserversFn,
|
|
812
803
|
) {
|
package/client/hooks.ts
ADDED
|
@@ -0,0 +1,775 @@
|
|
|
1
|
+
import { getENVVariable } from '@jsb188/app';
|
|
2
|
+
import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app';
|
|
3
|
+
import { delay } from '@jsb188/app/utils/logic';
|
|
4
|
+
import { isServerErrorGQL } from '@jsb188/graphql/utils';
|
|
5
|
+
import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
|
|
6
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
7
|
+
import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache/';
|
|
8
|
+
import { QUERY_EXPIRE_TIMES } from '../cache/config';
|
|
9
|
+
import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types.d';
|
|
10
|
+
import { graphqlRequest } from './request';
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Types; mutation
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type GraphQLMutationOptions = Partial<{
|
|
18
|
+
checkMountedBeforeCallback: boolean;
|
|
19
|
+
authToken: string;
|
|
20
|
+
retryCount: number;
|
|
21
|
+
variables: Record<string, any> | null;
|
|
22
|
+
cacheMap: any;
|
|
23
|
+
openModalPopUp: AnyModalPopUpFn | null;
|
|
24
|
+
initialError: any;
|
|
25
|
+
onCompleted: OnCompletedGQLFn;
|
|
26
|
+
onError: OnErrorGQLFn;
|
|
27
|
+
}>;
|
|
28
|
+
|
|
29
|
+
type GraphQLMutationResult = {
|
|
30
|
+
data: any | null;
|
|
31
|
+
variables: Record<string, any> | null;
|
|
32
|
+
saving: boolean;
|
|
33
|
+
error: ServerErrorObj | null;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
type GraphQLMutation = [
|
|
37
|
+
(graphqlOptions?: GraphQLRequestOptions, triedCount?: number) => Promise<any>,
|
|
38
|
+
GraphQLMutationResult,
|
|
39
|
+
GraphQLHandlers,
|
|
40
|
+
UpdateObserversFn,
|
|
41
|
+
React.MutableRefObject<boolean>
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Types; query
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
type GraphQLRequestOptions = {
|
|
49
|
+
variables?: Record<string, any> | null;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
type GraphQLQueryResult = {
|
|
53
|
+
data: any | null;
|
|
54
|
+
variables?: Record<string, any> | null;
|
|
55
|
+
loading: boolean;
|
|
56
|
+
error: ServerErrorObj | null;
|
|
57
|
+
refetch: () => void;
|
|
58
|
+
fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
|
|
59
|
+
variablesKey: string;
|
|
60
|
+
updatedCount: number;
|
|
61
|
+
updateObservers: UpdateObserversFn;
|
|
62
|
+
connectedToServer: boolean;
|
|
63
|
+
screenIsFocused: boolean;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Global variables
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
const QRY_TRACKER = new Map();
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Global; unset query tracker
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
function unsetQueryTracker(queryName: string, unique: string | null) {
|
|
77
|
+
const currentHookId = QRY_TRACKER.get(queryName);
|
|
78
|
+
if (currentHookId === unique) {
|
|
79
|
+
QRY_TRACKER.delete(queryName);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Helper; get retry delay
|
|
85
|
+
*/
|
|
86
|
+
|
|
87
|
+
function getRetryDelay(triedCount: number): number {
|
|
88
|
+
return 1500 * Math.pow(2, triedCount);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Update data observer
|
|
93
|
+
*/
|
|
94
|
+
|
|
95
|
+
export function useUpdateObservers(): UpdateObserversFn {
|
|
96
|
+
const setQueryObserver = useSetQueryObserver();
|
|
97
|
+
const setFragmentObserver = useSetFragmentObserver();
|
|
98
|
+
|
|
99
|
+
return (args: UpdateDataObserverArgs) => {
|
|
100
|
+
if (args.queryId) {
|
|
101
|
+
setQueryObserver((prev: any) => ({
|
|
102
|
+
count: (prev.name === args.queryId ? prev.count : 0) + 1,
|
|
103
|
+
name: args.queryId as string,
|
|
104
|
+
forceRefetch: !!args.forceRefetch,
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (args.fragmentIds?.length) {
|
|
109
|
+
setFragmentObserver((prev: any) => ({
|
|
110
|
+
count: (prev.count || 0) + 1,
|
|
111
|
+
list: args.fragmentIds as string[],
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Hook for query changes
|
|
119
|
+
*/
|
|
120
|
+
|
|
121
|
+
export function useWatchQuery(
|
|
122
|
+
query: any,
|
|
123
|
+
variablesKey: string,
|
|
124
|
+
): [number, boolean] { // [updatedCount, forceRefetch]
|
|
125
|
+
|
|
126
|
+
const queryObserver = useQueryObserverValue();
|
|
127
|
+
|
|
128
|
+
return useMemo(() => {
|
|
129
|
+
if (queryObserver.name) {
|
|
130
|
+
const matchedQry = query.definitions
|
|
131
|
+
.filter((d: any) => d.kind === 'OperationDefinition')
|
|
132
|
+
.find((d: any) => queryObserver.name.startsWith('#' + d.name.value));
|
|
133
|
+
|
|
134
|
+
if (!matchedQry) {
|
|
135
|
+
return [0, false];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// console.log('matchedQry:', matchedQry);
|
|
139
|
+
// console.log('queryObserver:', queryObserver);
|
|
140
|
+
|
|
141
|
+
const queryName = matchedQry.name.value;
|
|
142
|
+
const queryId = `#${queryName}:${variablesKey}`;
|
|
143
|
+
|
|
144
|
+
return [
|
|
145
|
+
queryObserver.name === queryId ? queryObserver.count : 0,
|
|
146
|
+
!!queryObserver.forceRefetch,
|
|
147
|
+
];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return [0, false];
|
|
151
|
+
}, [queryObserver]);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Hook for reactive fragment data
|
|
156
|
+
*/
|
|
157
|
+
|
|
158
|
+
export function useReactiveFragment(
|
|
159
|
+
data_: any,
|
|
160
|
+
observe: Array<string | string[]>,
|
|
161
|
+
qryObsCount?: number,
|
|
162
|
+
otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
|
|
163
|
+
ignoreIDWarning?: boolean,
|
|
164
|
+
// doTest?: boolean
|
|
165
|
+
) {
|
|
166
|
+
|
|
167
|
+
const data = data_ || {};
|
|
168
|
+
const fragmentObserver = useFragmentObserverValue();
|
|
169
|
+
const frgObsCount = fragmentObserver.count;
|
|
170
|
+
const [changedData, setChangedData] = useState<any>({
|
|
171
|
+
fragmentUpdatedCount: frgObsCount,
|
|
172
|
+
queryUpdatedCount: qryObsCount,
|
|
173
|
+
data
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
|
|
177
|
+
// this is fine because it will only run in development and never truly be conditional
|
|
178
|
+
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
if (
|
|
181
|
+
// getENVVariable('NODE_ENV') === 'development' &&
|
|
182
|
+
data.id && changedData.data?.id &&
|
|
183
|
+
data.id !== changedData.data?.id
|
|
184
|
+
) {
|
|
185
|
+
console.warn(`WARNING: useReactiveFragment() data.id changed from ${data.id} to ${changedData.data?.id}`);
|
|
186
|
+
console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
|
|
187
|
+
}
|
|
188
|
+
}, [changedData.data?.id]);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
useEffect(() => {
|
|
192
|
+
// NOTE: I tried this with effect()
|
|
193
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
194
|
+
// I only solved it by using useEffect()
|
|
195
|
+
const idsChanged = (
|
|
196
|
+
changedData.data.id !== data.id ||
|
|
197
|
+
(
|
|
198
|
+
// This is absolutely needed for the chat clientId system to work properly;
|
|
199
|
+
// Otherwise messages will be stuck in "not sent" state.
|
|
200
|
+
changedData.data.clientId &&
|
|
201
|
+
changedData.data.clientId !== data.clientId
|
|
202
|
+
)
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
const forceReactive = otherCheck && otherCheck(changedData.data, fragmentObserver.list);
|
|
206
|
+
|
|
207
|
+
if (
|
|
208
|
+
idsChanged ||
|
|
209
|
+
forceReactive || (
|
|
210
|
+
(changedData.data || data) &&
|
|
211
|
+
(
|
|
212
|
+
frgObsCount !== changedData.fragmentUpdatedCount ||
|
|
213
|
+
qryObsCount !== changedData.queryUpdatedCount
|
|
214
|
+
)
|
|
215
|
+
)
|
|
216
|
+
) {
|
|
217
|
+
|
|
218
|
+
// if (doTest) {
|
|
219
|
+
// console.log('DO TEST:');
|
|
220
|
+
// console.log(observe);
|
|
221
|
+
// console.log(fragmentObserver);
|
|
222
|
+
// }
|
|
223
|
+
|
|
224
|
+
let newData;
|
|
225
|
+
for (const key of observe) {
|
|
226
|
+
const isMapped = Array.isArray(key);
|
|
227
|
+
if (
|
|
228
|
+
key && (
|
|
229
|
+
idsChanged ||
|
|
230
|
+
forceReactive ||
|
|
231
|
+
(isMapped && fragmentObserver.list.includes(key[0])) ||
|
|
232
|
+
(!isMapped && fragmentObserver.list.includes(key))
|
|
233
|
+
)
|
|
234
|
+
) {
|
|
235
|
+
if (!newData) {
|
|
236
|
+
if (idsChanged) {
|
|
237
|
+
newData = data;
|
|
238
|
+
} else if (data) {
|
|
239
|
+
newData = {
|
|
240
|
+
...data,
|
|
241
|
+
...changedData.data,
|
|
242
|
+
};
|
|
243
|
+
} else {
|
|
244
|
+
newData = changedData.data;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const fragmentData = loadFragment(isMapped ? key[0] : key);
|
|
249
|
+
if (fragmentData) {
|
|
250
|
+
if (isMapped) {
|
|
251
|
+
newData = {
|
|
252
|
+
...newData,
|
|
253
|
+
[key[1]]: fragmentData,
|
|
254
|
+
};
|
|
255
|
+
} else {
|
|
256
|
+
newData = {
|
|
257
|
+
...newData,
|
|
258
|
+
...fragmentData,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (newData) {
|
|
266
|
+
setChangedData({
|
|
267
|
+
data: newData,
|
|
268
|
+
fragmentUpdatedCount: frgObsCount,
|
|
269
|
+
queryUpdatedCount: qryObsCount,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}, [data.id, qryObsCount, frgObsCount]);
|
|
274
|
+
|
|
275
|
+
// This is not needed now, I think
|
|
276
|
+
// useEffect(() => {
|
|
277
|
+
// if (updateQueryCount && queryKey) {
|
|
278
|
+
// const updatedQueryData = loadQuery(queryKey);
|
|
279
|
+
// setChangedData({
|
|
280
|
+
// ...changedData,
|
|
281
|
+
// data: {
|
|
282
|
+
// ...changedData.data,
|
|
283
|
+
// ...updatedQueryData,
|
|
284
|
+
// },
|
|
285
|
+
// });
|
|
286
|
+
// }
|
|
287
|
+
// }, [updateQueryCount]);
|
|
288
|
+
|
|
289
|
+
return changedData.data;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Observe query changes; but for Arrays
|
|
294
|
+
*/
|
|
295
|
+
|
|
296
|
+
export function useReactiveFragmentMap(
|
|
297
|
+
data: any[] | null,
|
|
298
|
+
fragmentName_: string,
|
|
299
|
+
) {
|
|
300
|
+
const fragmentName = `$${fragmentName_}`;
|
|
301
|
+
const observe = data?.map((d) => fragmentName + ':' + d.id);
|
|
302
|
+
const fragmentObserver = useFragmentObserverValue();
|
|
303
|
+
|
|
304
|
+
const [changedData, setChangedData] = useState({
|
|
305
|
+
count: fragmentObserver.count,
|
|
306
|
+
lastObserve: observe,
|
|
307
|
+
data
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
useEffect(() => {
|
|
311
|
+
// NOTE: I tried this with effect()
|
|
312
|
+
// But that caused the render to happen 3 times more, I don't know why.
|
|
313
|
+
// I only solved it by using useEffect()
|
|
314
|
+
|
|
315
|
+
const dataToUpdate = changedData.data || data;
|
|
316
|
+
if (
|
|
317
|
+
dataToUpdate &&
|
|
318
|
+
observe &&
|
|
319
|
+
fragmentObserver.count !== changedData.count
|
|
320
|
+
) {
|
|
321
|
+
let newData;
|
|
322
|
+
for (let i = 0; i < observe.length; i++) {
|
|
323
|
+
const key = observe[i];
|
|
324
|
+
|
|
325
|
+
if (fragmentObserver.list.includes(key)) {
|
|
326
|
+
if (!newData) {
|
|
327
|
+
newData = dataToUpdate;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (newData[i]) {
|
|
331
|
+
const fragmentData = loadFragment(key);
|
|
332
|
+
if (fragmentData) {
|
|
333
|
+
newData[i] = {
|
|
334
|
+
...newData[i],
|
|
335
|
+
...fragmentData,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (newData) {
|
|
343
|
+
setChangedData({
|
|
344
|
+
...changedData,
|
|
345
|
+
count: fragmentObserver.count,
|
|
346
|
+
data: newData.slice(0)
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}, [fragmentObserver.list]);
|
|
351
|
+
|
|
352
|
+
const observeStr = observe?.join(',');
|
|
353
|
+
useEffect(() => {
|
|
354
|
+
if (changedData.lastObserve?.join(',') !== observeStr) {
|
|
355
|
+
setChangedData({
|
|
356
|
+
...changedData,
|
|
357
|
+
data,
|
|
358
|
+
lastObserve: observe,
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
}, [observeStr]);
|
|
362
|
+
|
|
363
|
+
return changedData.data;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Use mutation
|
|
368
|
+
*/
|
|
369
|
+
|
|
370
|
+
export function useMutation(
|
|
371
|
+
mutation: any,
|
|
372
|
+
options?: GraphQLMutationOptions,
|
|
373
|
+
): GraphQLMutation {
|
|
374
|
+
|
|
375
|
+
const { onCompleted, onError, openModalPopUp, initialError, checkMountedBeforeCallback } = options || {};
|
|
376
|
+
const updateObservers = useUpdateObservers();
|
|
377
|
+
|
|
378
|
+
// No need to abort mutations
|
|
379
|
+
// But bring it back if you want ability to "cancel"
|
|
380
|
+
// const controller = useRef();
|
|
381
|
+
|
|
382
|
+
const mounted = useRef(true);
|
|
383
|
+
const [mtnValues, setMtnValues] = useState({
|
|
384
|
+
variables: null as Record<string, any> | null,
|
|
385
|
+
saving: false,
|
|
386
|
+
data: null,
|
|
387
|
+
error: initialError || null as ServerErrorObj | null
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
// Mounted hook
|
|
391
|
+
|
|
392
|
+
useEffect(() => {
|
|
393
|
+
return () => {
|
|
394
|
+
mounted.current = false;
|
|
395
|
+
};
|
|
396
|
+
}, []);
|
|
397
|
+
|
|
398
|
+
// Mutate function for the client
|
|
399
|
+
|
|
400
|
+
const doMutate = async (
|
|
401
|
+
graphqlOptions?: GraphQLRequestOptions,
|
|
402
|
+
triedCount: number = 0,
|
|
403
|
+
) => {
|
|
404
|
+
// No need to abort mutations
|
|
405
|
+
// if (controller.current) {
|
|
406
|
+
// controller.current.abort();
|
|
407
|
+
// }
|
|
408
|
+
|
|
409
|
+
// No need to abort mutations
|
|
410
|
+
// controller.current = new AbortController();
|
|
411
|
+
|
|
412
|
+
setMtnValues({
|
|
413
|
+
...mtnValues,
|
|
414
|
+
variables: graphqlOptions?.variables || null,
|
|
415
|
+
saving: true,
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
const retryCount = options?.retryCount || 0;
|
|
419
|
+
const retryDelay = getRetryDelay(triedCount);
|
|
420
|
+
|
|
421
|
+
const apiResult = await graphqlRequest(
|
|
422
|
+
mutation,
|
|
423
|
+
graphqlOptions?.variables,
|
|
424
|
+
{
|
|
425
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
|
|
426
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
427
|
+
if (mounted.current) {
|
|
428
|
+
setMtnValues({
|
|
429
|
+
...mtnValues,
|
|
430
|
+
saving: false,
|
|
431
|
+
data: data.data || null,
|
|
432
|
+
error,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (data.data) {
|
|
437
|
+
if (onCompleted && (mounted.current || !checkMountedBeforeCallback)) {
|
|
438
|
+
// Do separate {mounted.current} check from outside
|
|
439
|
+
onCompleted(data.data, error, graphqlOptions?.variables);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
},
|
|
443
|
+
onError: (error: ServerErrorObj | null) => {
|
|
444
|
+
if (mounted.current) {
|
|
445
|
+
setMtnValues({
|
|
446
|
+
...mtnValues,
|
|
447
|
+
saving: retryCount > triedCount,
|
|
448
|
+
error,
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (onError && retryCount <= triedCount && (mounted.current || !checkMountedBeforeCallback)) {
|
|
453
|
+
onError(error, graphqlOptions?.variables);
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
},
|
|
457
|
+
null, // abort controller is not needed for mutations
|
|
458
|
+
updateObservers
|
|
459
|
+
);
|
|
460
|
+
|
|
461
|
+
if (apiResult.aborted) {
|
|
462
|
+
return apiResult;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
466
|
+
if (retryCount > triedCount) {
|
|
467
|
+
await delay(retryDelay);
|
|
468
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
469
|
+
console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
return doMutate(graphqlOptions, triedCount + 1);
|
|
473
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
474
|
+
console.log(
|
|
475
|
+
`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return apiResult;
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
const mtnHandlers: GraphQLHandlers = {
|
|
484
|
+
resetErrors: function () {
|
|
485
|
+
setMtnValues({
|
|
486
|
+
...mtnValues,
|
|
487
|
+
error: null,
|
|
488
|
+
});
|
|
489
|
+
},
|
|
490
|
+
setError: function (errorObj: SimpleErrorType) {
|
|
491
|
+
setMtnValues({
|
|
492
|
+
...mtnValues,
|
|
493
|
+
error: {
|
|
494
|
+
...errorObj,
|
|
495
|
+
statusCode: 200,
|
|
496
|
+
errorCode: 'custom_error',
|
|
497
|
+
},
|
|
498
|
+
});
|
|
499
|
+
},
|
|
500
|
+
refetch: function () {
|
|
501
|
+
const lastVariables = mtnValues.variables;
|
|
502
|
+
return doMutate(lastVariables ? { variables: lastVariables } : undefined);
|
|
503
|
+
},
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
// useEffect(() => {
|
|
507
|
+
// return () => {
|
|
508
|
+
// if (controller.current) {
|
|
509
|
+
// controller.current.abort();
|
|
510
|
+
// }
|
|
511
|
+
// };
|
|
512
|
+
// }, []);
|
|
513
|
+
|
|
514
|
+
return [doMutate, mtnValues, mtnHandlers, updateObservers, mounted];
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Use query
|
|
519
|
+
*/
|
|
520
|
+
|
|
521
|
+
export function useQuery(
|
|
522
|
+
query: any,
|
|
523
|
+
options?: GraphQLQueryOptions,
|
|
524
|
+
): GraphQLQueryResult {
|
|
525
|
+
const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap } = options || {};
|
|
526
|
+
const variablesKey = makeVariablesKey(variables);
|
|
527
|
+
const connectedToServer = useConnectedToServerValue();
|
|
528
|
+
const screenIsFocused = useScreenIsFocusedValue();
|
|
529
|
+
const updateObservers = useUpdateObservers();
|
|
530
|
+
const [updatedCount, forceRefetch] = useWatchQuery(query, variablesKey);
|
|
531
|
+
|
|
532
|
+
// useQuery() assumes query is a single graphql query (and not a multi/chain)
|
|
533
|
+
// Multiple queries can be chained using this hook,
|
|
534
|
+
// but only the first query is used for tracking reactivity.
|
|
535
|
+
const queryName = query.definitions?.[0]?.name?.value;
|
|
536
|
+
const queryKey = queryName + ':' + variablesKey;
|
|
537
|
+
|
|
538
|
+
const tracker = useRef({
|
|
539
|
+
unique: null as string | null,
|
|
540
|
+
abortCtrl: null as AbortController | null,
|
|
541
|
+
reconnectedAt: null as number | null,
|
|
542
|
+
init: false
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// check if p.updatedCount is needed
|
|
546
|
+
|
|
547
|
+
const [qryValues, setQryValues] = useState({
|
|
548
|
+
data: null as any,
|
|
549
|
+
variables,
|
|
550
|
+
loading: false,
|
|
551
|
+
error: null as ServerErrorObj | null,
|
|
552
|
+
lastUpdatedCount: 0
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
// Query function for the client
|
|
556
|
+
// NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
|
|
557
|
+
|
|
558
|
+
const doQuery = async (queryVariables?: any, triedCount: number = 0) => {
|
|
559
|
+
|
|
560
|
+
const currentHookId = QRY_TRACKER.get(queryKey);
|
|
561
|
+
|
|
562
|
+
if (!currentHookId) {
|
|
563
|
+
QRY_TRACKER.set(queryKey, tracker.current.unique);
|
|
564
|
+
} else if (currentHookId) {
|
|
565
|
+
// This query is being fetched already, so do nothing
|
|
566
|
+
// This can happen in 2 ways;
|
|
567
|
+
// 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
|
|
568
|
+
// 2. useWatchQuery() caused 2 hooks with same query to be called at once
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (tracker.current.abortCtrl && qryValues.loading) {
|
|
573
|
+
// doLog(query, 'Query component [$0] is being aborted before being refetched.');
|
|
574
|
+
// console.log('ABORT:', queryKey, tracker.current.unique);
|
|
575
|
+
tracker.current.abortCtrl.abort({
|
|
576
|
+
name: 'AbortError',
|
|
577
|
+
message: `Hook for ${queryKey} has aborted because the [query refetched before the previous one ended].`
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
tracker.current.abortCtrl = new AbortController();
|
|
582
|
+
|
|
583
|
+
setQryValues({
|
|
584
|
+
...qryValues,
|
|
585
|
+
loading: true,
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
const retryCount = options?.retryCount || 0;
|
|
589
|
+
const retryDelay = getRetryDelay(triedCount);
|
|
590
|
+
const qryVariables = queryVariables || variables;
|
|
591
|
+
// const qryName = query.definitions?.[0]?.name?.value;
|
|
592
|
+
|
|
593
|
+
// doLog(query, 'Query component [$0] is being refetched.');
|
|
594
|
+
|
|
595
|
+
const apiResult = await graphqlRequest(
|
|
596
|
+
query,
|
|
597
|
+
qryVariables,
|
|
598
|
+
{
|
|
599
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
|
|
600
|
+
cacheMap,
|
|
601
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
602
|
+
if (data.data) {
|
|
603
|
+
setQryValues({
|
|
604
|
+
...qryValues,
|
|
605
|
+
variables: qryVariables,
|
|
606
|
+
data: data.data,
|
|
607
|
+
loading: false,
|
|
608
|
+
error,
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
if (onCompleted) {
|
|
612
|
+
onCompleted(data.data, error, qryVariables);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
removeStaleCache();
|
|
616
|
+
tracker.current.reconnectedAt = Date.now();
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
unsetQueryTracker(queryKey, tracker.current.unique);
|
|
620
|
+
},
|
|
621
|
+
onError: (error: ServerErrorObj | null) => {
|
|
622
|
+
setQryValues({
|
|
623
|
+
...qryValues,
|
|
624
|
+
variables: qryVariables,
|
|
625
|
+
loading: retryCount > triedCount,
|
|
626
|
+
error,
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
if (onError && retryCount <= triedCount) {
|
|
630
|
+
onError(error, qryVariables);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
unsetQueryTracker(queryKey, tracker.current.unique);
|
|
634
|
+
},
|
|
635
|
+
},
|
|
636
|
+
tracker.current.abortCtrl.signal,
|
|
637
|
+
updateObservers
|
|
638
|
+
);
|
|
639
|
+
|
|
640
|
+
if (apiResult.aborted) {
|
|
641
|
+
return apiResult;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
645
|
+
if (retryCount > triedCount) {
|
|
646
|
+
await delay(retryDelay);
|
|
647
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
648
|
+
console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
return doQuery(queryVariables, triedCount + 1);
|
|
652
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
653
|
+
console.log(
|
|
654
|
+
`query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return apiResult;
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
// Mount & unmount
|
|
663
|
+
|
|
664
|
+
useEffect(() => {
|
|
665
|
+
if (!tracker.current.unique) {
|
|
666
|
+
tracker.current.unique = Date.now().toString(36) + Math.random().toString(36).substring(2);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
return () => {
|
|
670
|
+
unsetQueryTracker(queryKey, tracker.current.unique);
|
|
671
|
+
|
|
672
|
+
if (tracker.current.abortCtrl) {
|
|
673
|
+
// console.log('UMOUNTED:', queryKey, tracker.current.unique);
|
|
674
|
+
tracker.current.abortCtrl.abort({
|
|
675
|
+
name: 'AbortError',
|
|
676
|
+
message: `Hook for ${queryKey} has aborted because [the component unmounted].`
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
}, [queryKey]);
|
|
681
|
+
|
|
682
|
+
// Refetch when variables, skip status or query observer changes
|
|
683
|
+
|
|
684
|
+
useEffect(() => {
|
|
685
|
+
if (
|
|
686
|
+
!skip && (
|
|
687
|
+
updatedCount !== qryValues.lastUpdatedCount ||
|
|
688
|
+
variablesKey !== makeVariablesKey(qryValues.variables) ||
|
|
689
|
+
!checkDataCompleteness(qryValues.data, query)
|
|
690
|
+
)
|
|
691
|
+
) {
|
|
692
|
+
const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
|
|
693
|
+
if (cachedResult) {
|
|
694
|
+
setQryValues({
|
|
695
|
+
...qryValues,
|
|
696
|
+
variables,
|
|
697
|
+
data: cachedResult,
|
|
698
|
+
error: null,
|
|
699
|
+
loading: false, // IMPORTANT: must be false here
|
|
700
|
+
lastUpdatedCount: updatedCount || 0,
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
if (forceRefetch && !qryValues.loading) {
|
|
704
|
+
doQuery();
|
|
705
|
+
// console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
|
|
706
|
+
// console.log('::', variablesKey, skip, updatedCount);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
} else if (!qryValues.loading) {
|
|
710
|
+
// doLog(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
|
|
711
|
+
doQuery();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}, [variablesKey, skip, updatedCount]);
|
|
715
|
+
|
|
716
|
+
// Refetch when the app reconnects and has no data
|
|
717
|
+
|
|
718
|
+
const withoutData = qryValues.data === null;
|
|
719
|
+
const reconnectedWithoutData = !skip && withoutData && !qryValues.loading && connectedToServer;
|
|
720
|
+
|
|
721
|
+
useEffect(() => {
|
|
722
|
+
if (connectedToServer && screenIsFocused && !skip) {
|
|
723
|
+
const now = Date.now();
|
|
724
|
+
|
|
725
|
+
let timeDiff, timeThresh;
|
|
726
|
+
if (reconnectedWithoutData) {
|
|
727
|
+
timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : Infinity;
|
|
728
|
+
timeThresh = 5000;
|
|
729
|
+
} else {
|
|
730
|
+
timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : -Infinity;
|
|
731
|
+
timeThresh = QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// console.log('>>', queryName, timeDiff, timeThresh);
|
|
735
|
+
|
|
736
|
+
if (
|
|
737
|
+
tracker.current.init &&
|
|
738
|
+
timeDiff > timeThresh
|
|
739
|
+
) {
|
|
740
|
+
// console.log('query again:', queryName, timeDiff);
|
|
741
|
+
// doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
|
|
742
|
+
tracker.current.reconnectedAt = now;
|
|
743
|
+
doQuery();
|
|
744
|
+
} else {
|
|
745
|
+
tracker.current.init = true;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}, [reconnectedWithoutData, screenIsFocused]);
|
|
749
|
+
|
|
750
|
+
const refetch = useCallback(() => {
|
|
751
|
+
return doQuery();
|
|
752
|
+
}, [doQuery]);
|
|
753
|
+
|
|
754
|
+
const fetchMore = useCallback((obj: GraphQLRequestOptions): Promise<any> => {
|
|
755
|
+
return doQuery(obj?.variables);
|
|
756
|
+
}, [doQuery]);
|
|
757
|
+
|
|
758
|
+
return {
|
|
759
|
+
...qryValues,
|
|
760
|
+
data: loadDataFromCache(
|
|
761
|
+
qryValues.data,
|
|
762
|
+
query,
|
|
763
|
+
variablesKey,
|
|
764
|
+
cacheMap,
|
|
765
|
+
eagerFragmentKeyMap,
|
|
766
|
+
),
|
|
767
|
+
variablesKey,
|
|
768
|
+
refetch,
|
|
769
|
+
fetchMore,
|
|
770
|
+
updatedCount,
|
|
771
|
+
updateObservers,
|
|
772
|
+
connectedToServer,
|
|
773
|
+
screenIsFocused,
|
|
774
|
+
};
|
|
775
|
+
}
|
package/client/index.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { getENVVariable } from '@jsb188/app';
|
|
2
|
+
import type { ServerErrorObj } from '@jsb188/app/types/app';
|
|
3
|
+
import { getAuthToken, normalizeServerError } from '@jsb188/app/utils/api';
|
|
4
|
+
import { delay } from '@jsb188/app/utils/logic';
|
|
5
|
+
import { setDataToCache } from '../cache/';
|
|
6
|
+
import type { OnCompletedGQLFn, OnErrorGQLFn, UpdateObserversFn } from '../types.d';
|
|
7
|
+
import { apiRequestHeaders, isServerErrorGQL } from '../utils';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Types
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
type GraphQLMutationOptions = Partial<{
|
|
14
|
+
authToken: string;
|
|
15
|
+
retryCount: number;
|
|
16
|
+
variables: any;
|
|
17
|
+
cacheMap: any;
|
|
18
|
+
openModalPopUp: any;
|
|
19
|
+
initialError: any;
|
|
20
|
+
onCompleted: OnCompletedGQLFn;
|
|
21
|
+
onError: OnErrorGQLFn;
|
|
22
|
+
}>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Helper: Get name of query
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
// function getQueryName(query: any) {
|
|
29
|
+
// return query.definitions.filter((d: any) => d.kind === 'OperationDefinition').map(d => d.name.value).join(', ');
|
|
30
|
+
// }
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Helper; Log if conditions are met
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
// function doLog(query: any, logStr: string) {
|
|
37
|
+
// const queryName = getQueryName(query);
|
|
38
|
+
// if (queryName === 'friend') {
|
|
39
|
+
// console.log(logStr.replace(/\$0/gi, queryName));
|
|
40
|
+
// }
|
|
41
|
+
// }
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Default params for graphql requests
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
const defaultRequestParams = {
|
|
48
|
+
// onCompleted: (data: any) => {
|
|
49
|
+
// if (getENVVariable('NODE_ENV') === 'development') {
|
|
50
|
+
// console.log('onCompleted:', data);
|
|
51
|
+
// }
|
|
52
|
+
// },
|
|
53
|
+
onError: (error: ServerErrorObj | null) => {
|
|
54
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
55
|
+
console.log('DEVELOPMENT onError():', error);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* GraphQL request with retry support
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
export async function graphqlRequestWithRetry(
|
|
65
|
+
gqlQuery: any,
|
|
66
|
+
graphqlOptions: GraphQLMutationOptions = defaultRequestParams,
|
|
67
|
+
triedCount: number = 0,
|
|
68
|
+
): Promise<any> {
|
|
69
|
+
|
|
70
|
+
const retryCount = graphqlOptions?.retryCount || 0;
|
|
71
|
+
const retryDelay = 1500 * Math.pow(2, triedCount);
|
|
72
|
+
const { onCompleted, onError, openModalPopUp } = graphqlOptions;
|
|
73
|
+
|
|
74
|
+
const apiResult = await graphqlRequest(
|
|
75
|
+
gqlQuery,
|
|
76
|
+
graphqlOptions?.variables,
|
|
77
|
+
{
|
|
78
|
+
openModalPopUp: retryCount >= triedCount ? openModalPopUp : undefined,
|
|
79
|
+
onCompleted: (data: any | null, error: ServerErrorObj | null) => {
|
|
80
|
+
if (onCompleted && data.data) {
|
|
81
|
+
onCompleted(data.data, error, graphqlOptions?.variables);
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
onError: (error: ServerErrorObj | null) => {
|
|
85
|
+
if (onError && retryCount <= triedCount) {
|
|
86
|
+
onError(error, graphqlOptions?.variables);
|
|
87
|
+
} else if (!onError) {
|
|
88
|
+
console.warn(error);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
if (!apiResult.data && isServerErrorGQL(apiResult)) {
|
|
95
|
+
if (retryCount > triedCount) {
|
|
96
|
+
await delay(retryDelay);
|
|
97
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
98
|
+
console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return graphqlRequestWithRetry(gqlQuery, graphqlOptions, triedCount + 1);
|
|
102
|
+
} else if (getENVVariable('NODE_ENV') === 'development') {
|
|
103
|
+
console.log(
|
|
104
|
+
`mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return apiResult.data || apiResult;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* GraphQL query
|
|
114
|
+
*/
|
|
115
|
+
|
|
116
|
+
export async function graphqlRequest(
|
|
117
|
+
gqlQuery: any,
|
|
118
|
+
variables?: any,
|
|
119
|
+
params?: GraphQLMutationOptions,
|
|
120
|
+
controllerSignal?: AbortSignal | null,
|
|
121
|
+
updateObservers?: UpdateObserversFn,
|
|
122
|
+
): Promise<any> {
|
|
123
|
+
|
|
124
|
+
const { openModalPopUp, onCompleted, onError, authToken, cacheMap } = params || {};
|
|
125
|
+
|
|
126
|
+
if (!gqlQuery?.definitions) {
|
|
127
|
+
console.log(gqlQuery);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const operationName = gqlQuery?.definitions?.find((def: any) => def.kind === 'OperationDefinition')?.name?.value;
|
|
131
|
+
const headers = apiRequestHeaders(getENVVariable('IS_BROWSER') ? getAuthToken() : authToken);
|
|
132
|
+
|
|
133
|
+
// Use this to check queries that are getting double-requested
|
|
134
|
+
// doLog(gqlQuery, 'QUERYING... $0');
|
|
135
|
+
|
|
136
|
+
return fetch(getENVVariable('GQL_SERVER')!, {
|
|
137
|
+
signal: controllerSignal,
|
|
138
|
+
method: 'POST',
|
|
139
|
+
// credentials: 'same-origin',
|
|
140
|
+
// headers: new Headers({
|
|
141
|
+
headers: new Headers(headers),
|
|
142
|
+
// headers,
|
|
143
|
+
body: JSON.stringify({
|
|
144
|
+
query: gqlQuery?.loc?.source.body,
|
|
145
|
+
variables,
|
|
146
|
+
operationName,
|
|
147
|
+
}),
|
|
148
|
+
})
|
|
149
|
+
.then((response) => response.json())
|
|
150
|
+
.then((data) => {
|
|
151
|
+
let gqlError: ServerErrorObj | null = null;
|
|
152
|
+
if (data.errors?.length) {
|
|
153
|
+
gqlError = normalizeServerError(data);
|
|
154
|
+
|
|
155
|
+
if (openModalPopUp) {
|
|
156
|
+
openModalPopUp(null, gqlError);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (onError) {
|
|
160
|
+
onError(gqlError, variables);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (onCompleted) {
|
|
165
|
+
onCompleted(data, gqlError, variables);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
setDataToCache(data.data, gqlQuery, variables, cacheMap, updateObservers);
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
...data.data,
|
|
172
|
+
error: gqlError,
|
|
173
|
+
};
|
|
174
|
+
})
|
|
175
|
+
.catch((err) => {
|
|
176
|
+
if (getENVVariable('NODE_ENV') === 'development') {
|
|
177
|
+
console.log(err);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (err.name === 'AbortError') {
|
|
181
|
+
return { aborted: true };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const gqlError = normalizeServerError(err);
|
|
185
|
+
if (openModalPopUp) {
|
|
186
|
+
openModalPopUp(null, gqlError);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (onError) {
|
|
190
|
+
onError(gqlError, variables);
|
|
191
|
+
}
|
|
192
|
+
return { error: gqlError };
|
|
193
|
+
});
|
|
194
|
+
}
|
|
@@ -4,21 +4,13 @@ import { aiChatFragment, aiChatMessageFragment } from '../fragments/aiChatFragme
|
|
|
4
4
|
export const aiChatQry = gql`
|
|
5
5
|
query aiChat (
|
|
6
6
|
$aiChatId: GenericID!
|
|
7
|
-
$cursor: Cursor
|
|
8
|
-
$after: Boolean!
|
|
9
|
-
$limit: Int!
|
|
10
7
|
) {
|
|
11
8
|
aiChat (
|
|
12
9
|
aiChatId: $aiChatId
|
|
13
10
|
) {
|
|
14
11
|
...aiChatFragment
|
|
15
12
|
|
|
16
|
-
messages
|
|
17
|
-
cursor: $cursor
|
|
18
|
-
after: $after
|
|
19
|
-
limit: $limit
|
|
20
|
-
) {
|
|
21
|
-
cursor
|
|
13
|
+
messages {
|
|
22
14
|
...aiChatMessageFragment
|
|
23
15
|
}
|
|
24
16
|
}
|
|
@@ -27,3 +19,23 @@ query aiChat (
|
|
|
27
19
|
${aiChatFragment}
|
|
28
20
|
${aiChatMessageFragment}
|
|
29
21
|
`;
|
|
22
|
+
|
|
23
|
+
export const aiChatMessagesQry = gql`
|
|
24
|
+
query aiChatMessages (
|
|
25
|
+
$aiChatId: GenericID!
|
|
26
|
+
$cursor: Cursor
|
|
27
|
+
$after: Boolean!
|
|
28
|
+
$limit: Int!
|
|
29
|
+
) {
|
|
30
|
+
aiChatMessages (
|
|
31
|
+
aiChatId: $aiChatId
|
|
32
|
+
cursor: $cursor
|
|
33
|
+
after: $after
|
|
34
|
+
limit: $limit
|
|
35
|
+
) {
|
|
36
|
+
...aiChatMessageFragment
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
${aiChatMessageFragment}
|
|
41
|
+
`;
|
package/package.json
CHANGED
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jsb188/graphql",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"description": "GraphQL client for react, using recoil",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"author": "jsb188",
|
|
7
7
|
"type": "module",
|
|
8
|
-
"main": "main.ts",
|
|
9
8
|
"types": "types.d.ts",
|
|
10
9
|
"exports": {
|
|
11
|
-
".": "./main.ts",
|
|
12
10
|
"./fragments/auth": "./gql/fragments/authFragments.ts",
|
|
13
11
|
"./fragments/aiChat": "./gql/fragments/aiChatFragments.ts",
|
|
14
12
|
"./fragments/billing": "./gql/fragments/billingFragments.ts",
|
|
@@ -29,14 +27,21 @@
|
|
|
29
27
|
"./queries/chat": "./gql/queries/chatQueries.ts",
|
|
30
28
|
"./queries/other": "./gql/queries/otherQueries.ts",
|
|
31
29
|
"./queries/user": "./gql/queries/userQueries.ts",
|
|
30
|
+
"./cache": "./cache/index.ts",
|
|
31
|
+
"./client": "./client/index.ts",
|
|
32
|
+
"./sse": "./sse.ts",
|
|
32
33
|
"./types": "./types.d.ts",
|
|
33
|
-
"./utils": "./
|
|
34
|
+
"./utils": "./utils.ts"
|
|
34
35
|
},
|
|
35
36
|
"scripts": {
|
|
36
37
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
37
38
|
},
|
|
38
39
|
"dependencies": {
|
|
39
|
-
"graphql
|
|
40
|
-
"
|
|
40
|
+
"graphql": "^16.10.0",
|
|
41
|
+
"graphql-tag": "^2.12.6"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@jsb188/app": "^1.0.4",
|
|
45
|
+
"@jsb188/react": "^1.0.4"
|
|
41
46
|
}
|
|
42
47
|
}
|
package/sse.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { UpdateObserversFn } from './types.d';
|
|
2
|
+
import { loadFragment, updateQuery, updateFragment, addFragmentToCache } from './cache/';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Types
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
type ValidSSEType = (
|
|
9
|
+
// Default SSE events
|
|
10
|
+
'CONNECTED' |
|
|
11
|
+
// Query handlers
|
|
12
|
+
'QUERY_APPEND' | 'QUERY_PREPEND' |
|
|
13
|
+
// Fragment handlers
|
|
14
|
+
'DATA_APPEND' | 'DATA_PREPEND' | 'DATA_UPDATE'
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
interface PublishPayload {
|
|
18
|
+
__type: ValidSSEType;
|
|
19
|
+
fragmentKey: string;
|
|
20
|
+
fragmentNamespace?: string;
|
|
21
|
+
dataFragmentKey?: string;
|
|
22
|
+
data: Record<string, any>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Append or prepend data to a query
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
function handleQueryConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
|
|
30
|
+
|
|
31
|
+
const { __type, fragmentKey, fragmentNamespace, dataFragmentKey, data } = payload;
|
|
32
|
+
if (fragmentKey && fragmentNamespace && dataFragmentKey && data) {
|
|
33
|
+
const isAppend = __type === 'QUERY_APPEND';
|
|
34
|
+
|
|
35
|
+
const updateData = (currentData: any) => {
|
|
36
|
+
const currentList = currentData?.[fragmentNamespace]?.data;
|
|
37
|
+
if (
|
|
38
|
+
currentData?.[fragmentNamespace]?.__list &&
|
|
39
|
+
Array.isArray(currentList) &&
|
|
40
|
+
!currentList.find(a => a[0] === dataFragmentKey)
|
|
41
|
+
) {
|
|
42
|
+
addFragmentToCache(dataFragmentKey, data);
|
|
43
|
+
const updatedList = isAppend ? [...currentList, [dataFragmentKey]] : [[dataFragmentKey], ...currentList];
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
...currentData,
|
|
47
|
+
[fragmentNamespace]: {
|
|
48
|
+
...currentData?.[fragmentNamespace],
|
|
49
|
+
data: updatedList
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return currentData;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
updateQuery(
|
|
57
|
+
fragmentKey,
|
|
58
|
+
updateData,
|
|
59
|
+
false,
|
|
60
|
+
updateObservers
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Append or prepend data to a fragment
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
function handleFragmentConcat(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
|
|
70
|
+
const { __type, fragmentKey, fragmentNamespace, data } = payload;
|
|
71
|
+
const isAppend = __type === 'DATA_APPEND';
|
|
72
|
+
|
|
73
|
+
if (fragmentKey && fragmentNamespace && data) {
|
|
74
|
+
const namespaceType = typeof fragmentNamespace;
|
|
75
|
+
const updateData = (currentData: any) => {
|
|
76
|
+
if (typeof currentData[fragmentNamespace] === namespaceType) {
|
|
77
|
+
|
|
78
|
+
let nextValue;
|
|
79
|
+
if (namespaceType === 'string') {
|
|
80
|
+
nextValue = isAppend ? `${currentData[fragmentNamespace]}${data}` : `${data}${currentData[fragmentNamespace]}`;
|
|
81
|
+
} else if (Array.isArray(currentData[fragmentNamespace])) {
|
|
82
|
+
nextValue = isAppend ? [...currentData[fragmentNamespace], data] : [data, ...currentData[fragmentNamespace]];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
...currentData,
|
|
87
|
+
[fragmentNamespace]: nextValue
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return currentData;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
updateFragment(fragmentKey, updateData, null, isAppend, updateObservers);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Update data in a fragment
|
|
100
|
+
*/
|
|
101
|
+
|
|
102
|
+
function handleFragmentUpdate(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
|
|
103
|
+
const { fragmentKey, dataFragmentKey, data } = payload;
|
|
104
|
+
updateFragment(dataFragmentKey || fragmentKey, data, null, false, updateObservers);
|
|
105
|
+
|
|
106
|
+
console.log(
|
|
107
|
+
loadFragment(fragmentKey),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Data handler for SSE
|
|
114
|
+
*/
|
|
115
|
+
|
|
116
|
+
function handleSSEData(payload: PublishPayload, updateObservers?: UpdateObserversFn) {
|
|
117
|
+
|
|
118
|
+
switch (payload.__type) {
|
|
119
|
+
case 'CONNECTED':
|
|
120
|
+
// Do nothing
|
|
121
|
+
break;
|
|
122
|
+
case 'QUERY_APPEND':
|
|
123
|
+
case 'QUERY_PREPEND':
|
|
124
|
+
handleQueryConcat(payload, updateObservers)
|
|
125
|
+
break;
|
|
126
|
+
case 'DATA_APPEND':
|
|
127
|
+
case 'DATA_PREPEND':
|
|
128
|
+
handleFragmentConcat(payload, updateObservers)
|
|
129
|
+
break;
|
|
130
|
+
case 'DATA_UPDATE':
|
|
131
|
+
handleFragmentUpdate(payload, updateObservers)
|
|
132
|
+
break;
|
|
133
|
+
default:
|
|
134
|
+
console.log('Unknown {__type} in handleSSEData():', payload.__type);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export default handleSSEData;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getENVVariable } from '@jsb188/app';
|
|
1
2
|
import type { ServerErrorObj } from '@jsb188/app/types/app';
|
|
2
3
|
|
|
3
4
|
const TIME_TRACKER = new Map();
|
|
@@ -54,3 +55,30 @@ export function isServerErrorGQL(apiResult: any): boolean {
|
|
|
54
55
|
apiResult?.error?.errorCode === 'network_error'
|
|
55
56
|
);
|
|
56
57
|
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Headers for all network requests
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
export function apiRequestHeaders(authorization: string | null | undefined): any {
|
|
64
|
+
const headers = {
|
|
65
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
66
|
+
api_key: getENVVariable('GQL_API_KEY'),
|
|
67
|
+
origin: getENVVariable('APP_URL'),
|
|
68
|
+
'Access-Control-Allow-Origin': getENVVariable('APP_URL'),
|
|
69
|
+
// recaptcha: ? // Not sure if we're going to do this later any more
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
if (!getENVVariable('IS_BROWSER')) {
|
|
73
|
+
// @ts-expect-error Can't allow undefined or null
|
|
74
|
+
headers.ssr = '1';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (authorization) {
|
|
78
|
+
// Do not send undefined or null, it will become a String type
|
|
79
|
+
// @ts-expect-error Can't allow undefined or null
|
|
80
|
+
headers.authorization = authorization;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return headers;
|
|
84
|
+
}
|
package/main.ts
DELETED