@jsb188/graphql 1.0.0

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/index.ts ADDED
@@ -0,0 +1,861 @@
1
+ import type { UpdateObserversFn } from '../types.d';
2
+ import { RULES, PARTIALS_MAP } from './config';
3
+
4
+ const DO_LOG = [
5
+ false, // [0] Log name
6
+ false, // [1] Log data
7
+ ];
8
+
9
+ const QUERIES = new Map();
10
+ const FRAGMENTS = new Map();
11
+
12
+ /**
13
+ * JS Map will sometimes convert nested Array into Array-like Object
14
+ * ie. "{"0": "a", "1": "b"}" etc
15
+ * This will convert Array-like back to Array
16
+ *
17
+ * NOTE: There's a known vulnerability here that sometimes the developer may
18
+ * actually design a Array-like schema; but I don't see a need for that right now.
19
+ */
20
+
21
+ function enforceArrayType(obj: any): any {
22
+ if (obj && typeof obj === 'object') {
23
+ if (Array.isArray(obj)) {
24
+ return obj.map(enforceArrayType);
25
+ }
26
+
27
+ const keys = Object.keys(obj);
28
+ if (keys.every((key, i) => key === i.toString())) {
29
+ return keys.map((key) => obj[key]);
30
+ }
31
+
32
+ for (const key in obj) {
33
+ if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'object') {
34
+ obj[key] = enforceArrayType(obj[key]);
35
+ }
36
+ }
37
+ }
38
+ return obj;
39
+ }
40
+
41
+ /**
42
+ * Merge nested objects together
43
+ */
44
+
45
+ export function mergeNestedObjects(obj1: any, obj2: any) {
46
+ if (!obj1) {
47
+ return { ...obj2 };
48
+ }
49
+
50
+ const newObj = { ...obj1 };
51
+ for (const key in obj2) {
52
+ if (Object.prototype.hasOwnProperty.call(obj2, key)) {
53
+ if (typeof obj2[key] === 'object' && obj2[key] !== null) {
54
+ newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
55
+ } else {
56
+ newObj[key] = obj2[key];
57
+ }
58
+ }
59
+ }
60
+
61
+ return newObj;
62
+ }
63
+
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
+ /**
82
+ * Get a single string to represent all variables for a query
83
+ * NOTE: This isn't perfect because variables could have extra or unnnecessary keys/values
84
+ * The correct way to do this would be to compare it against the query {variableDefinitions}
85
+ * But this will work as long as each variables object is used consistently to match the used query.
86
+ */
87
+
88
+ export function makeVariablesKey(variables?: any) {
89
+ if (variables) {
90
+ const key = Object.keys(variables).sort().reduce((acc, key) => {
91
+ const value = variables[key];
92
+ if (value || value === 0 || value === false) {
93
+ return `${acc}$${key}:${value}`;
94
+ }
95
+ return acc;
96
+ }, '');
97
+
98
+ // NOTE: I can't think of a query where capitalization matters;
99
+ // So I'm doing lowerCase() here.
100
+ // Also, I don't think there's any query where null/undefined matters;
101
+ // So I'm omitting all of those.
102
+
103
+ return key.toLowerCase();
104
+ }
105
+ return 'none';
106
+ }
107
+
108
+ /**
109
+ * Make Object for fragment, omitting what you don't need
110
+ */
111
+
112
+ function extractFragment(dataObj: any, innerSelection: any[]) {
113
+ if (innerSelection.length <= 1) {
114
+ return dataObj;
115
+ }
116
+
117
+ const fragmentObj = { ...dataObj };
118
+ for (const sel of innerSelection) {
119
+ if (sel.kind === 'Field') {
120
+ delete fragmentObj[sel.name.value];
121
+ }
122
+ }
123
+
124
+ return fragmentObj;
125
+ }
126
+
127
+ /**
128
+ * Load query cache
129
+ */
130
+
131
+ export function loadQuery(queryKey: string, referencesOnly?: boolean) {
132
+ const references = QUERIES.get(queryKey);
133
+ if (referencesOnly) {
134
+ return references;
135
+ } else if (!references) {
136
+ // This is important, not returning null will cause infinite loop
137
+ return null;
138
+ }
139
+
140
+ if (Array.isArray(references)) {
141
+ const mappedCache = references.map((cacheObj) => appendFragmentToCache(cacheObj));
142
+ if (mappedCache.some((c) => !c)) {
143
+ return undefined;
144
+ }
145
+
146
+ // let hasInvalidatedCache = false;
147
+ // const mappedCache = references.map((cacheObj) => {
148
+ // if (!hasInvalidatedCache) {
149
+ // const singleCache = appendFragmentToCache(cacheObj);
150
+
151
+ // if (singleCache) {
152
+ // return singleCache;
153
+ // } else {
154
+ // hasInvalidatedCache = true;
155
+ // }
156
+ // }
157
+ // });
158
+ // if (!hasInvalidatedCache) {
159
+ // return mappedCache;
160
+ // }
161
+
162
+ return mappedCache;
163
+ } else if (references) {
164
+ const singleCacheData = appendFragmentToCache(references);
165
+ return singleCacheData;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Load fragment cache
171
+ */
172
+
173
+ export function loadFragment(id: string) {
174
+ return enforceArrayType(FRAGMENTS.get(id));
175
+ }
176
+
177
+ /**
178
+ * Map each inner selection under a graphql query object
179
+ */
180
+
181
+ function mapSelections(data: any, innerSelections: any[], updatedKeys: string[] = []) {
182
+ return innerSelections.map((inner) => {
183
+ if (inner.kind === 'FragmentSpread') {
184
+ const frgName = inner.name.value;
185
+ const frgMap = PARTIALS_MAP[frgName];
186
+ const fragmentKey = `$${frgMap || frgName}:${data.id || 'none'}`;
187
+
188
+ if (DO_LOG[0]) {
189
+ console.log('SETTING (1): ', fragmentKey);
190
+ }
191
+ if (DO_LOG[1]) {
192
+ console.log('SETTING (1): ', extractFragment(data, innerSelections));
193
+ }
194
+
195
+ // if (key === 'messages') {
196
+ // console.log('---->', data.id);
197
+ // }
198
+
199
+ // Whether fragment is partial or not, always merge data;
200
+ // Because partials might have data that's not in the main fragment
201
+ const currentData = loadFragment(fragmentKey);
202
+
203
+ // FRAGMENTS.delete(fragmentKey);
204
+ FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, extractFragment(data, innerSelections)));
205
+ updatedKeys.push(fragmentKey);
206
+
207
+ return fragmentKey;
208
+ }
209
+
210
+ return [inner.name.value, data?.[inner.name.value]];
211
+ // return {
212
+ // name: inner.name.value,
213
+ // value: data[key]?.[inner.name.value]
214
+ // };
215
+ });
216
+ }
217
+
218
+ /**
219
+ * Make cache object from data and selection object
220
+ */
221
+
222
+ function makeCacheObject(data: any, selections: any[], variables?: any, cacheMap?: any) {
223
+ const cacheObj: Record<string, any> = {};
224
+ const updatedKeys: string[] = [];
225
+
226
+ for (const sel of selections) {
227
+ const key = sel.name.value;
228
+ if (!data[key] && sel.kind !== 'FragmentSpread') {
229
+ // console.log('~~~', key, sel.kind);
230
+ continue;
231
+ }
232
+
233
+ // if (DO_LOG[2]) {
234
+ // console.log(sel);
235
+ // }
236
+
237
+ switch (sel.kind) {
238
+ case 'Field':
239
+ {
240
+ const innerSelections = sel.selectionSet?.selections;
241
+ if (innerSelections) {
242
+ if (Array.isArray(data[key])) {
243
+ cacheObj[key] = {
244
+ __cache: true,
245
+ __list: true,
246
+ data: data[key].map((item) => mapSelections(item, innerSelections, updatedKeys)),
247
+ };
248
+ } else {
249
+ cacheObj[key] = {
250
+ __cache: true,
251
+ data: mapSelections(data[key], innerSelections, updatedKeys),
252
+ };
253
+ }
254
+ } else {
255
+ cacheObj[key] = data[key];
256
+ }
257
+ }
258
+ break;
259
+ case 'FragmentSpread':
260
+ {
261
+ const frgName = sel.name.value;
262
+ const frgMap = PARTIALS_MAP[frgName];
263
+ const fragmentKey = `$${frgMap || frgName}:${data.id || 'none'}`;
264
+
265
+ if (RULES[frgName] !== false) {
266
+ if (DO_LOG[0]) {
267
+ console.log('SETTING (2): ', fragmentKey);
268
+ }
269
+ if (DO_LOG[1]) {
270
+ console.log('SETTING (2): ', extractFragment(data, selections));
271
+ }
272
+
273
+ // if (testMode) {
274
+ // console.log('Array.isArray(data)');
275
+ // console.log(Array.isArray(data));
276
+ // console.log(data);
277
+ // console.log(extractFragment(data, selections));
278
+ // }
279
+
280
+ // Whether fragment is partial or not, always merge data;
281
+ // Because partials might have data that's not in the main fragment
282
+ const currentData = loadFragment(fragmentKey);
283
+
284
+ // FRAGMENTS.delete(fragmentKey);
285
+ FRAGMENTS.set(fragmentKey, mergeNestedObjects(currentData, extractFragment(data, selections)));
286
+ updatedKeys.push(fragmentKey);
287
+ }
288
+
289
+ cacheObj.__flat = {
290
+ __cache: true,
291
+ data: [fragmentKey],
292
+ };
293
+ }
294
+ break;
295
+ default:
296
+ }
297
+
298
+ // If there's a cache map, return a custom value
299
+ // This will make the cache object NOT get set into the query cache
300
+ // This means that cache IS handled but the values will be invalid
301
+ // so cacheMap has to handle the cache object itself
302
+
303
+ if (cacheMap?.[key]) {
304
+ const customCacheData = cacheMap[key](data[key], cacheObj[key], sel, variables);
305
+ cacheObj[key] = typeof customCacheData === 'undefined' ? null : customCacheData;
306
+ continue;
307
+ }
308
+ }
309
+
310
+ return [cacheObj, updatedKeys];
311
+ }
312
+
313
+ /**
314
+ * Save query cache
315
+ */
316
+
317
+ function saveQueryToMemory(
318
+ requestData: any | null,
319
+ selection: any,
320
+ variables: any,
321
+ variablesKey: string,
322
+ cacheMap?: any,
323
+ saveQueryToCache?: boolean,
324
+ updateObservers?: UpdateObserversFn,
325
+ ) {
326
+ const qryName = selection.name.value;
327
+ if (!requestData) {
328
+ return;
329
+ }
330
+
331
+ const data = requestData[qryName];
332
+ const queryId = `#${qryName}:${variablesKey}`;
333
+ const selections = selection?.selectionSet?.selections;
334
+
335
+ if (!selections) {
336
+ return;
337
+ }
338
+
339
+ if (data) {
340
+ // console.log('=====');
341
+ // console.log(requestData);
342
+ // console.log(queryId);
343
+ // console.log(data);
344
+ // console.log('=====');
345
+
346
+ const cacheMapObj = typeof cacheMap === 'function' ? null : cacheMap;
347
+
348
+ let cacheData;
349
+ let updatedFragmentIds;
350
+ if (Array.isArray(data)) {
351
+ const result = data.map((dataObj) => makeCacheObject(dataObj, selections, variables, cacheMapObj));
352
+ cacheData = result.map((r) => r[0]);
353
+ updatedFragmentIds = result.reduce((acc, r) => acc.concat(r[1]), []);
354
+ } else {
355
+ [cacheData, updatedFragmentIds] = makeCacheObject(data, selections, variables, cacheMapObj);
356
+ }
357
+
358
+ // console.log(updatedFragmentIds);
359
+ // console.log(cacheData);
360
+
361
+ if (typeof cacheMap === 'function') {
362
+ // cacheMap[key](data[key], cacheObj[key], sel, variables);
363
+ if (saveQueryToCache) {
364
+ const customCacheData = cacheMap(data, cacheData, selections, variables);
365
+ // console.log('--->', queryId);
366
+
367
+ QUERIES.set(queryId, typeof customCacheData === 'undefined' ? null : customCacheData);
368
+
369
+ if (updateObservers) {
370
+ updateObservers({
371
+ queryId
372
+ });
373
+ }
374
+ }
375
+ } else {
376
+ if (saveQueryToCache) {
377
+ // console.log('--->', queryId);
378
+ QUERIES.set(queryId, cacheData);
379
+ }
380
+
381
+ if (updateObservers) {
382
+ updateObservers({
383
+ queryId: saveQueryToCache ? queryId : null,
384
+ fragmentIds: updatedFragmentIds as string[],
385
+ });
386
+ }
387
+
388
+ // I don't think observer is needed for custom cache maps, but if it does, bring it up
389
+ // FRAGMENT_OBSERVER.value = {
390
+ // count: FRAGMENT_OBSERVER.value.count + 1,
391
+ // list: updatedFragmentIds,
392
+ // };
393
+ }
394
+
395
+ return updatedFragmentIds;
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Recursively update fragments after a mutation/query
401
+ */
402
+
403
+ /**
404
+ * Save cache
405
+ */
406
+
407
+ export function setDataToCache(
408
+ requestData: any,
409
+ gqlQuery: any,
410
+ variables?: any,
411
+ cacheMap?: any,
412
+ updateObservers?: UpdateObserversFn,
413
+ ) {
414
+ // query[variablesKey] = cache;
415
+ const definitions = gqlQuery.definitions;
416
+ const variablesKey = makeVariablesKey(variables);
417
+
418
+ for (const def of definitions) {
419
+ if (def.kind === 'OperationDefinition') {
420
+ def?.selectionSet?.selections.forEach((selection: any) => {
421
+ const qryName = selection.name?.value;
422
+ saveQueryToMemory(
423
+ requestData,
424
+ selection,
425
+ variables,
426
+ variablesKey,
427
+ cacheMap,
428
+ !!RULES[qryName],
429
+ updateObservers
430
+ );
431
+ });
432
+ }
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Append fragment to cache
438
+ */
439
+
440
+ export function appendFragmentToCache(cacheData: any) {
441
+ let newObj = cloneArrayLike(cacheData);
442
+
443
+ for (const key in newObj) {
444
+ if (newObj[key] && typeof newObj[key] === 'object' && newObj[key].__cache && newObj[key].data) {
445
+ const isFlat = key === '__flat';
446
+
447
+ let cachedObj = {};
448
+ let cacheIsValid = true;
449
+
450
+ if (newObj[key].__list) {
451
+ cachedObj = newObj[key].data.map((di) => {
452
+ let item = {};
453
+ di.forEach((d) => {
454
+ if (Array.isArray(d)) {
455
+ item[d[0]] = d[1];
456
+ } else if (typeof d === 'string') {
457
+ const frgIndex = d.indexOf(':');
458
+ const frgName = d.substring(1, frgIndex);
459
+ const frgMap = PARTIALS_MAP[frgName];
460
+
461
+ let fragmentKey;
462
+ if (frgMap) {
463
+ fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
464
+ } else {
465
+ fragmentKey = d;
466
+ }
467
+
468
+ const cachedFragment = loadFragment(fragmentKey);
469
+ if (DO_LOG[0]) {
470
+ console.log('LOAD (1): ', d);
471
+ }
472
+ if (DO_LOG[1]) {
473
+ console.log('LOAD (1): ', cachedFragment);
474
+ }
475
+
476
+ if (cachedFragment) {
477
+ item = {
478
+ ...item,
479
+ ...cachedFragment,
480
+ };
481
+ } else {
482
+ // Cache was invalidated
483
+ cacheIsValid = false;
484
+ }
485
+ }
486
+ });
487
+
488
+ return item;
489
+ });
490
+ } else {
491
+ newObj[key].data.forEach((d) => {
492
+ if (Array.isArray(d)) {
493
+ cachedObj[d[0]] = d[1];
494
+ } else if (typeof d === 'string') {
495
+ const frgIndex = d.indexOf(':');
496
+ const frgName = d.substring(1, frgIndex);
497
+ const frgMap = PARTIALS_MAP[frgName];
498
+
499
+ let fragmentKey;
500
+ if (frgMap) {
501
+ fragmentKey = `$${frgMap}:${d.substring(frgIndex + 1)}`;
502
+ } else {
503
+ fragmentKey = d;
504
+ }
505
+
506
+ const cachedFragment = loadFragment(fragmentKey);
507
+ if (DO_LOG[0]) {
508
+ console.log('LOAD (2): ', d);
509
+ }
510
+ if (DO_LOG[1]) {
511
+ console.log('LOAD (2): ', cachedFragment);
512
+ }
513
+
514
+ if (cachedFragment) {
515
+ if (isFlat) {
516
+ newObj = {
517
+ ...newObj,
518
+ ...cachedFragment,
519
+ };
520
+ delete newObj.__flat;
521
+ } else {
522
+ cachedObj = {
523
+ ...cachedObj,
524
+ ...cachedFragment,
525
+ };
526
+ }
527
+ } else {
528
+ // Cache was invalidated
529
+ cacheIsValid = false;
530
+ }
531
+ }
532
+ });
533
+ }
534
+
535
+ if (!cacheIsValid) {
536
+ return null;
537
+ }
538
+
539
+ if (!isFlat) {
540
+ newObj[key] = cachedObj;
541
+ }
542
+ }
543
+ }
544
+
545
+ return newObj;
546
+ }
547
+
548
+ /**
549
+ * Get cache
550
+ */
551
+
552
+ export function loadDataFromCache(
553
+ requestData: any | null,
554
+ gqlQuery: any,
555
+ variablesKey: string,
556
+ cacheMap?: any,
557
+ eagerFragmentKeyMap?: any,
558
+ ) {
559
+ // return query[variablesKey];
560
+ const data = { ...requestData };
561
+ const definitions = gqlQuery.definitions;
562
+
563
+ for (const def of definitions) {
564
+ if (def.kind === 'OperationDefinition') {
565
+ def?.selectionSet?.selections.forEach((selection) => {
566
+ const qryName = selection.name?.value;
567
+ if (!data[qryName]) {
568
+ const cacheKey = `#${qryName}:${variablesKey}`;
569
+ const cachedData = loadQuery(cacheKey);
570
+
571
+ if (cachedData) {
572
+ data[qryName] = cachedData;
573
+ }
574
+
575
+ // const cacheData = QUERIES.get(cacheKey);
576
+
577
+ // if (Array.isArray(cacheData)) {
578
+ // let hasInvalidatedCache = false;
579
+ // const mappedCache = cacheData.map((cacheObj, i) => {
580
+ // if (!hasInvalidatedCache) {
581
+ // const singleCache = appendFragmentToCache(cacheObj);
582
+
583
+ // if (singleCache) {
584
+ // return singleCache;
585
+ // } else {
586
+ // hasInvalidatedCache = true;
587
+ // }
588
+ // }
589
+ // });
590
+
591
+ // if (!hasInvalidatedCache) {
592
+ // data[qryName] = mappedCache;
593
+ // }
594
+ // } else if (cacheData) {
595
+ // const singleCacheData = appendFragmentToCache(cacheData);
596
+
597
+ // if (singleCacheData) {
598
+ // data[qryName] = singleCacheData;
599
+ // }
600
+ // }
601
+ }
602
+
603
+ // Set value to "true" because this is meant to be handled by a cacheMap and its standalone logic
604
+
605
+ if (data[qryName]) {
606
+ if (typeof cacheMap === 'function') {
607
+ data[qryName] = true;
608
+ } else if (cacheMap) {
609
+ for (const key in cacheMap) {
610
+ if (cacheMap?.[key] && data[qryName]?.[key] !== undefined) {
611
+ data[qryName][key] = true;
612
+ }
613
+ }
614
+ }
615
+ } else if (eagerFragmentKeyMap?.[qryName]) {
616
+ const fragmentKey = eagerFragmentKeyMap[qryName];
617
+ const cachedFragment = loadFragment(fragmentKey);
618
+
619
+ if (cachedFragment) {
620
+ data[qryName] = cachedFragment;
621
+ }
622
+ }
623
+ });
624
+ }
625
+ }
626
+
627
+ return data;
628
+ }
629
+
630
+ /**
631
+ * Check if request data is complete
632
+ */
633
+
634
+ export function checkDataCompleteness(requestData: any, gqlQuery: any) {
635
+ if (!requestData) {
636
+ return false;
637
+ }
638
+
639
+ const definitions = gqlQuery.definitions;
640
+ for (const def of definitions) {
641
+ if (def.kind === 'OperationDefinition') {
642
+ const selections = def?.selectionSet?.selections;
643
+ for (const selection of selections) {
644
+ const qryName = selection.name?.value;
645
+ const value = requestData[qryName];
646
+ if (!value && value !== false && value !== 0) {
647
+ return false;
648
+ }
649
+ }
650
+ }
651
+ }
652
+
653
+ return true;
654
+ }
655
+
656
+ /**
657
+ * Invalidate stale cache
658
+ */
659
+
660
+ export function removeStaleCache() {
661
+ // function getByteSize(oMap){
662
+ // function replacer(key, value) {
663
+ // if(value instanceof Map) {
664
+ // return {
665
+ // dataType: 'Map',
666
+ // value: [...value],
667
+ // };
668
+ // } else {
669
+ // return value;
670
+ // }
671
+ // }
672
+ // return JSON.stringify(oMap, replacer).length;
673
+ // }
674
+
675
+ // console.log(' Queries cache size (count):', QUERIES.size);
676
+ // console.log(' Queries cache size (bytes):', getByteSize(QUERIES));
677
+ // console.log('Fragments cache size (count):', FRAGMENTS.size);
678
+ // console.log('Fragments cache size (bytes):', getByteSize(FRAGMENTS));
679
+
680
+ if (FRAGMENTS.size > RULES.__limit) {
681
+ const keys = Array.from(FRAGMENTS.keys());
682
+ const numToEvict = keys.length - RULES.__limit;
683
+
684
+ if (numToEvict > 0) {
685
+ const keysToEvict = keys.slice(0, numToEvict);
686
+
687
+ for (const key of keysToEvict) {
688
+ FRAGMENTS.delete(key);
689
+ }
690
+ }
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Check if there is cache
696
+ */
697
+
698
+ export function fetchCachedData(gqlQuery: any, variablesKey: string, updateObservers: UpdateObserversFn) {
699
+ const definitions = gqlQuery.definitions;
700
+
701
+ for (const def of definitions) {
702
+ if (def.kind === 'OperationDefinition') {
703
+ const selections = def?.selectionSet?.selections;
704
+ for (const selection of selections) {
705
+ const qryName = selection.name?.value;
706
+ const queryId = `#${qryName}:${variablesKey}`;
707
+
708
+ const cachedData = loadQuery(queryId);
709
+ if (cachedData === null) {
710
+ return null;
711
+ }
712
+
713
+ if (!cachedData) {
714
+ QUERIES.delete(queryId);
715
+
716
+ updateObservers({
717
+ queryId
718
+ });
719
+
720
+ return null;
721
+ }
722
+ return { [qryName]: cachedData };
723
+ }
724
+ }
725
+ }
726
+
727
+ return null;
728
+ }
729
+
730
+ /**
731
+ * Clear all cache
732
+ */
733
+
734
+ export function clearGraphQLClientCache() {
735
+ QUERIES.clear();
736
+ FRAGMENTS.clear();
737
+ }
738
+
739
+ /**
740
+ * Clear query cache
741
+ */
742
+
743
+ export function resetQuery(queryId: string, forceRefetch?: boolean, updateObservers?: UpdateObserversFn) {
744
+ // if (forceRefetch) {
745
+ // QUERIES.delete(queryId);
746
+ // }
747
+
748
+ if (updateObservers) {
749
+ updateObservers({
750
+ queryId,
751
+ forceRefetch,
752
+ });
753
+ }
754
+ }
755
+
756
+ /**
757
+ * Update cache
758
+ */
759
+
760
+ export function updateFragment(
761
+ id: string,
762
+ update: any | ((cache: any) => object),
763
+ replaceId?: string | null,
764
+ doNotTriggerObserver?: boolean,
765
+ updateObservers?: UpdateObserversFn,
766
+ ) {
767
+ const cache = loadFragment(id);
768
+
769
+ if (cache && update) {
770
+ let updateObj;
771
+ if (typeof update === 'function') {
772
+ updateObj = update(cache);
773
+ } else {
774
+ updateObj = update;
775
+ }
776
+
777
+ const updatedObj = { ...cache, ...updateObj };
778
+
779
+ FRAGMENTS.set(id, updatedObj);
780
+
781
+ if (replaceId && replaceId !== id) {
782
+ FRAGMENTS.set(replaceId, updatedObj);
783
+
784
+ // Must be deleted later, for the observer to work properly
785
+ // setTimeout(() => FRAGMENTS.delete(id), 1000);
786
+ }
787
+
788
+ if (!doNotTriggerObserver && updateObservers) {
789
+ updateObservers({
790
+ fragmentIds: [id],
791
+ });
792
+
793
+ // FRAGMENT_OBSERVER.value = {
794
+ // count: FRAGMENT_OBSERVER.value.count + 1,
795
+ // list: [id],
796
+ // };
797
+ }
798
+ return id || null;
799
+ }
800
+ return null;
801
+ }
802
+
803
+ /**
804
+ * Update query cache
805
+ */
806
+
807
+ export function updateQuery(
808
+ queryId: string,
809
+ update: any | ((cache: any) => object),
810
+ doNotTriggerObserver?: boolean,
811
+ updateObservers?: UpdateObserversFn,
812
+ ) {
813
+ const cache = loadQuery(queryId, true);
814
+ if (cache && update) {
815
+ let updateObj;
816
+ if (typeof update === 'function') {
817
+ updateObj = update(cache);
818
+ } else {
819
+ updateObj = update;
820
+ }
821
+
822
+ const updatedObj = Array.isArray(updateObj) ? updateObj : { ...cache, ...updateObj };
823
+ QUERIES.set(queryId, updatedObj);
824
+
825
+ if (!doNotTriggerObserver && updateObservers) {
826
+ updateObservers({
827
+ queryId,
828
+ });
829
+ }
830
+ return updateObj || null;
831
+ }
832
+ return null;
833
+ }
834
+
835
+ /**
836
+ * Bulk update cache
837
+ * NOTE: When you do updateFragment() twice, second call will override the first call;
838
+ * This will make observer NOT work.
839
+ */
840
+
841
+ export function triggerObserver(ids: (string | null)[], updateObservers?: UpdateObserversFn) {
842
+ if (updateObservers) {
843
+ const observerListIds = ids.filter((id) => id);
844
+ if (observerListIds.length) {
845
+ updateObservers({
846
+ fragmentIds: observerListIds,
847
+ });
848
+ }
849
+ } else {
850
+ console.warn('trigerObserver() was called without updateObservers(); This does nothing.');
851
+ }
852
+ }
853
+
854
+ /**
855
+ * Add to cache (be careful because this should always sync with server somehow)
856
+ */
857
+
858
+ export function addFragmentToCache(id: string, obj: any) {
859
+ // FRAGMENTS.delete(id);
860
+ FRAGMENTS.set(id, obj);
861
+ }