-
-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathresources.js
More file actions
2296 lines (2136 loc) · 70.2 KB
/
resources.js
File metadata and controls
2296 lines (2136 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
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
470
471
472
473
474
475
476
477
478
479
480
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
641
642
643
644
645
646
647
648
649
650
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Dexie from 'dexie';
import Mutex from 'mutex-js';
import findIndex from 'lodash/findIndex';
import flatMap from 'lodash/flatMap';
import isArray from 'lodash/isArray';
import isString from 'lodash/isString';
import matches from 'lodash/matches';
import overEvery from 'lodash/overEvery';
import sortBy from 'lodash/sortBy';
import compact from 'lodash/compact';
import uniq from 'lodash/uniq';
import uniqBy from 'lodash/uniqBy';
import { v4 as uuidv4 } from 'uuid';
import {
CHANGE_TYPES,
CHANGES_TABLE,
PAGINATION_TABLE,
RELATIVE_TREE_POSITIONS,
TABLE_NAMES,
COPYING_STATUS,
COPYING_STATUS_VALUES,
TASK_ID,
CURRENT_USER,
MAX_REV_KEY,
LAST_FETCHED,
CREATION_CHANGE_TYPES,
TREE_CHANGE_TYPES,
} from './constants';
import applyChanges, { applyMods, collectChanges } from './applyRemoteChanges';
import mergeAllChanges from './mergeChanges';
import db, { channelScope, CLIENTID, Collection } from './db';
import { API_RESOURCES, INDEXEDDB_RESOURCES, changeRevs } from './registry';
import {
CreatedChange,
UpdatedChange,
DeletedChange,
MovedChange,
CopiedChange,
PublishedChange,
SyncedChange,
DeployedChange,
UpdatedDescendantsChange,
} from './changes';
import urls from 'shared/urls';
import { currentLanguage } from 'shared/i18n';
import client, { paramsSerializer } from 'shared/client';
import { DELAYED_VALIDATION, fileErrors, NEW_OBJECT } from 'shared/constants';
import { ContentKindsNames } from 'shared/leUtils/ContentKinds';
import { getMergedMapFields } from 'shared/utils/helpers';
// Number of seconds after which data is considered stale.
const REFRESH_INTERVAL = 5;
const QUERY_SUFFIXES = {
IN: 'in',
GT: 'gt',
GTE: 'gte',
LT: 'lt',
LTE: 'lte',
};
const ORDER_FIELD = 'ordering';
const PAGINATION_FIELD = 'max_results';
const VALID_SUFFIXES = new Set(Object.values(QUERY_SUFFIXES));
const SUFFIX_SEPERATOR = '__';
const validPositions = new Set(Object.values(RELATIVE_TREE_POSITIONS));
const EMPTY_ARRAY = Symbol('EMPTY_ARRAY');
let vuexStore;
export function injectVuexStore(store) {
vuexStore = store;
}
function getUserIdFromStore() {
if (vuexStore) {
return vuexStore.getters.currentUserId;
}
throw ReferenceError(
```
Attempted to get the user_id from the store to set on a change object,
but the store has not been injected into the resources.js module using injectVuexStore function
```
);
}
// Custom uuid4 function to match our dashless uuids on the server side
export function uuid4() {
return uuidv4().replace(/-/g, '');
}
/*
* Code to allow multiple inheritance in JS
* modified from https://hacks.mozilla.org/2015/08/es6-in-depth-subclassing/
*/
function mix(...mixins) {
// Inherit from the last class to allow constructor inheritance
class Mix extends mixins.slice(-1)[0] {}
// Programmatically add all the methods and accessors
// of the mixins to class Mix.
for (const mixin of mixins) {
copyProperties(Mix, mixin);
copyProperties(Mix.prototype, mixin.prototype);
}
return Mix;
}
function copyProperties(target, source) {
for (const key of Reflect.ownKeys(source)) {
if (key !== 'constructor' && key !== 'prototype' && key !== 'name') {
const desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(target, key, desc);
}
}
}
function objectsAreStale(objs) {
const now = Date.now();
return objs.some(obj => {
const refresh = obj[LAST_FETCHED] + REFRESH_INTERVAL * 1000;
return refresh < now;
});
}
class APIResource {
constructor({ urlName, ...options }) {
this.urlName = urlName;
copyProperties(this, options);
API_RESOURCES[urlName] = this;
}
getUrlFunction(endpoint) {
return urls[`${this.urlName}_${endpoint}`];
}
modelUrl(id) {
// Leveraging Django REST Framework generated URL patterns.
return this.getUrlFunction('detail')(id);
}
collectionUrl() {
// Leveraging Django REST Framework generated URL patterns.
return this.getUrlFunction('list')();
}
fetchModel(id) {
return client.get(this.modelUrl(id));
}
fetchCollection(params) {
return client.get(this.collectionUrl(), { params });
}
}
class IndexedDBResource {
constructor({
tableName,
idField = 'id',
uuid = true,
indexFields = [],
syncable = false,
...options
} = {}) {
this.tableName = tableName;
// Don't allow resources with a compound index to have uuids
this.uuid = uuid && idField.split('+').length === 1;
this.schema = [idField, ...indexFields].join(',');
this.rawIdField = idField;
this.indexFields = new Set([idField, ...indexFields]);
INDEXEDDB_RESOURCES[tableName] = this;
copyProperties(this, options);
// By default these resources do not sync changes to the backend.
this.syncable = syncable;
}
get table() {
if (process.env.NODE_ENV !== 'production' && !db[this.tableName]) {
/* eslint-disable no-console */
console.error(
`Tried to access table ${this.tableName} but it does not exist. Either requires a migration or clearing indexedDB`
);
/* eslint-enable */
}
return db[this.tableName];
}
get idField() {
return this.table.schema.primKey.keyPath;
}
getIdValue(datum) {
if (typeof this.idField === 'string') {
return datum[this.idField];
}
return this.idField.map(f => datum[f]);
}
/*
* Transaction method used to invoke updates, creates and deletes
* in a way that doesn't trigger listeners from the client that
* initiated it by setting the CLIENTID.
*/
transaction({ mode = 'rw', source = null } = {}, ...extraTables) {
const callback = extraTables.pop();
if (source === null) {
source = CLIENTID;
}
return db.transaction(mode, this.tableName, ...extraTables, () => {
Dexie.currentTransaction.source = source;
return callback();
});
}
/**
* Search the "updated descendants" changes of the current resource and its
* parents to find any changes that should be applied to the current resource.
* And it transforms these "updated descendants" changes into "updated" changes
* to the current resource.
* @returns
*/
async getInheritedChanges(itemData = []) {
if (this.tableName !== TABLE_NAMES.CONTENTNODE || !itemData.length) {
return Promise.resolve([]);
}
const updatedDescendantsChanges = await db[CHANGES_TABLE].where('type')
.equals(CHANGE_TYPES.UPDATED_DESCENDANTS)
.toArray();
if (!updatedDescendantsChanges.length) {
return Promise.resolve([]);
}
const inheritedChanges = [];
const parentIds = [...new Set(itemData.map(item => item.parent).filter(Boolean))];
const ancestorsPromises = parentIds.map(parentId => this.getAncestors(parentId));
const parentsAncestors = await Promise.all(ancestorsPromises);
parentsAncestors.forEach(ancestors => {
const parent = ancestors[ancestors.length - 1];
const ancestorsIds = ancestors.map(ancestor => ancestor.id);
const parentChanges = updatedDescendantsChanges.filter(change =>
ancestorsIds.includes(change.key)
);
if (!parentChanges.length) {
return;
}
itemData
.filter(item => item.parent === parent.id)
.forEach(item => {
inheritedChanges.push(
...parentChanges.map(change => ({
...change,
mods: {
...change.mods,
...getMergedMapFields(item, change.mods),
},
key: item.id,
type: CHANGE_TYPES.UPDATED,
}))
);
});
});
return inheritedChanges;
}
mergeDescendantsChanges(changes, inheritedChanges, itemData) {
if (inheritedChanges.length) {
changes.push(...inheritedChanges);
changes = sortBy(changes, 'rev');
}
changes
.filter(change => change.type === CHANGE_TYPES.UPDATED_DESCENDANTS)
.forEach(change => {
change.type = CHANGE_TYPES.UPDATED;
const item = itemData.find(i => i.id === change.key);
if (!item) {
return;
}
change.mods = {
...change.mods,
...getMergedMapFields(item, change.mods),
};
});
return changes;
}
setData(itemData) {
const now = Date.now();
// Directly write to the table, rather than using the add/update methods
// to avoid creating change events that we would sync back to the server.
return this.transaction({ mode: 'rw' }, this.tableName, CHANGES_TABLE, () => {
// Get any relevant changes that would be overwritten by this bulkPut
const changesPromise = db[CHANGES_TABLE].where('[table+key]')
.anyOf(itemData.map(datum => [this.tableName, this.getIdValue(datum)]))
.sortBy('rev');
const inheritedChangesPromise = this.getInheritedChanges(itemData);
const currentPromise = this.table
.where(this.idField)
.anyOf(itemData.map(datum => this.getIdValue(datum)))
.toArray();
return Promise.all([changesPromise, inheritedChangesPromise, currentPromise]).then(
([changes, inheritedChanges, currents]) => {
changes = this.mergeDescendantsChanges(changes, inheritedChanges, itemData);
changes = mergeAllChanges(changes, true);
const collectedChanges = collectChanges(changes)[this.tableName] || {};
for (const changeType of Object.keys(collectedChanges)) {
const map = {};
for (const change of collectedChanges[changeType]) {
map[change.key] = change;
}
collectedChanges[changeType] = map;
}
const currentMap = {};
for (const currentObj of currents) {
currentMap[this.getIdValue(currentObj)] = currentObj;
}
const data = itemData
.map(datum => {
const id = this.getIdValue(datum);
datum[LAST_FETCHED] = now;
// Persist TASK_ID and COPYING_STATUS attributes when directly
// fetching from the server
if (currentMap[id] && currentMap[id][TASK_ID]) {
datum[TASK_ID] = currentMap[id][TASK_ID];
}
if (currentMap[id] && currentMap[id][COPYING_STATUS]) {
datum[COPYING_STATUS] = currentMap[id][COPYING_STATUS];
}
// If we have an updated change, apply the modifications here
if (
collectedChanges[CHANGE_TYPES.UPDATED] &&
collectedChanges[CHANGE_TYPES.UPDATED][id]
) {
applyMods(datum, collectedChanges[CHANGE_TYPES.UPDATED][id].mods);
}
return datum;
// If we have a deleted change, just filter out this object so we don't reput it
})
.filter(
datum =>
!collectedChanges[CHANGE_TYPES.DELETED] ||
!collectedChanges[CHANGE_TYPES.DELETED][this.getIdValue(datum)]
);
return this.table.bulkPut(data).then(() => {
// Move changes need to be reapplied on top of fetched data in case anything
// has happened on the backend.
return applyChanges(Object.values(collectedChanges[CHANGE_TYPES.MOVED] || {})).then(
results => {
if (!results || !results.length) {
return data;
}
const resultsMap = {};
for (const result of results) {
const id = this.getIdValue(result);
resultsMap[id] = result;
}
return data
.map(datum => {
const id = this.getIdValue(datum);
if (resultsMap[id]) {
applyMods(datum, resultsMap[id]);
}
return datum;
// Concatenate any unsynced created objects onto
// the end of the returned objects
})
.concat(Object.values(collectedChanges[CHANGE_TYPES.CREATED]).map(c => c.obj));
}
);
});
}
);
});
}
async where(params = {}) {
const table = db[this.tableName];
// Indexed parameters
const whereParams = {};
// Non-indexed parameters
const filterParams = {};
// Array parameters - ones that are filtering by 'in'
const arrayParams = {};
// Suffixed parameters - ones that are filtering by [gt/lt](e)
const suffixedParams = {};
// Field to sort by
let sortBy;
let reverse;
// Check for pagination
const maxResults = Number(params[PAGINATION_FIELD]);
const paginationActive = !isNaN(maxResults);
if (paginationActive && !params[ORDER_FIELD]) {
params[ORDER_FIELD] = this.defaultOrdering;
}
for (const key of Object.keys(params)) {
if (key === PAGINATION_FIELD) {
// Don't filter by parameters that are used for pagination
continue;
}
// Partition our parameters
const [rootParam, suffix] = key.split(SUFFIX_SEPERATOR);
if (suffix && VALID_SUFFIXES.has(suffix) && suffix !== QUERY_SUFFIXES.IN) {
// We have a suffix and it is for an operation that isn't IN
suffixedParams[rootParam] = suffixedParams[rootParam] || {};
suffixedParams[rootParam][suffix] = params[key];
} else if (this.indexFields.has(rootParam)) {
if (suffix === QUERY_SUFFIXES.IN) {
// We have a suffix for an IN operation
arrayParams[rootParam] = params[key];
} else if (!suffix) {
whereParams[rootParam] = params[key];
}
} else if (key === ORDER_FIELD) {
const ordering = params[key];
if (ordering.indexOf('-') === 0) {
sortBy = ordering.substring(1);
reverse = true;
} else {
sortBy = ordering;
}
} else {
filterParams[rootParam] = params[key];
}
}
let collection;
if (Object.keys(arrayParams).length !== 0) {
if (Object.keys(arrayParams).length === 1) {
const anyOf = Object.values(arrayParams)[0];
if (anyOf.length === 0) {
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable no-console */
console.warn(`Tried to query ${Object.keys(arrayParams)[0]} with no values`);
}
return Promise.resolve(EMPTY_ARRAY);
}
const keyPath = Object.keys(arrayParams)[0];
collection = table.where(keyPath).anyOf(Object.values(arrayParams)[0]);
if (process.env.NODE_ENV !== 'production') {
// Flag a warning if we tried to filter by an Array and other where params
if (Object.keys(whereParams).length > 1) {
/* eslint-disable no-console */
console.warn(
`Tried to query ${Object.keys(whereParams).join(
', '
)} alongside array parameters which is not currently supported`
);
/* eslint-enable */
}
}
Object.assign(filterParams, whereParams);
if (sortBy === keyPath) {
sortBy = null;
}
} else if (Object.keys(arrayParams).length > 1) {
if (process.env.NODE_ENV !== 'production') {
// Flag a warning if we tried to filter by an Array and other where params
/* eslint-disable no-console */
console.warn(
`Tried to query multiple __in params ${Object.keys(arrayParams).join(
', '
)} which is not currently supported`
);
/* eslint-enable */
}
}
} else if (Object.keys(whereParams).length > 0) {
collection = table.where(whereParams);
if (whereParams[sortBy] && Object.keys(whereParams).length === 1) {
// If there is only one where parameter, then the collection should already be sorted
// by the index that it was queried by.
// https://dexie.org/docs/Collection/Collection.sortBy()#remarks
sortBy = null;
}
} else {
if (sortBy && this.indexFields.has(sortBy)) {
collection = table.orderBy(sortBy);
if (reverse) {
collection = collection.reverse();
}
sortBy = null;
} else {
collection = table.toCollection();
}
}
let filterFn;
if (Object.keys(filterParams).length !== 0) {
filterFn = matches(filterParams);
}
if (Object.keys(suffixedParams).length !== 0) {
// Reassign the filterFn to be a combination of all the suffixed parameter filters
// we are applying here, so require that the item passes all the operations
// hence, overEvery.
filterFn = overEvery(
[
// First generate a flat array of all suffix parameter filter functions
...flatMap(
Object.keys(suffixedParams),
// First we iterate over the specific parameters we are filtering over
key => {
// Then we iterate over the suffixes that we are filtering over
return Object.keys(suffixedParams[key]).map(suffix => {
// For each suffix, we have a specific value
const value = suffixedParams[key][suffix];
// Now return a filter function depending on the specific
// suffix that we have passed.
if (suffix === QUERY_SUFFIXES.LT) {
return item => item[key] < value;
} else if (suffix === QUERY_SUFFIXES.LTE) {
return item => item[key] <= value;
} else if (suffix === QUERY_SUFFIXES.GT) {
return item => item[key] > value;
} else if (suffix === QUERY_SUFFIXES.GTE) {
return item => item[key] >= value;
}
// Because of how we are initially generating these
// we should never get to here and returning undefined
});
}
),
// If there are filter Params, this will be defined
filterFn,
// If there were not, it will be undefined and filtered by the final filter
// In addition, in the unlikely case that the suffix was not recognized,
// this will filter out those cases too.
].filter(f => f)
);
}
if (filterFn) {
collection = collection.filter(filterFn);
}
if (paginationActive) {
let results;
if (sortBy) {
// If we still have a sortBy value here, then we have not sorted using orderBy
// so we need to sort here.
if (reverse) {
collection = collection.reverse();
}
results = (await collection.sortBy(sortBy)).slice(0, maxResults + 1);
} else {
results = await collection.limit(maxResults + 1).toArray();
}
const hasMore = results.length > maxResults;
return {
results: results.slice(0, maxResults),
more: hasMore
? {
...params,
lft__gt: results[maxResults - 1].lft,
}
: null,
};
}
if (sortBy) {
if (reverse) {
collection = collection.reverse();
}
collection = collection.sortBy(sortBy);
}
return collection.toArray();
}
whereLiveQuery(params = {}) {
return Dexie.liveQuery(() => this.where(params));
}
get(id) {
return this.table.get(id);
}
/**
* Method to remove the NEW_OBJECT and DELAYED_VALIDATION symbols
* property so we don't commit it to IndexedDB
* @param {Object} obj
* @return {Object}
*/
_cleanNew(obj) {
const out = {
...obj,
};
delete out[NEW_OBJECT];
delete out[DELAYED_VALIDATION];
return out;
}
_saveAndQueueChange(change) {
return change.saveChange().then(rev => {
if (rev !== null) {
changeRevs.push(rev);
}
});
}
async _updateChange(id, changes, oldObj = null) {
if (!this.syncable) {
return Promise.resolve();
}
if (!oldObj) {
oldObj = await this.table.get(id);
}
if (!oldObj) {
return Promise.resolve();
}
const change = new UpdatedChange({
key: id,
table: this.tableName,
oldObj,
changes,
source: CLIENTID,
});
return this._saveAndQueueChange(change);
}
update(id, changes) {
return this.transaction({ mode: 'rw' }, CHANGES_TABLE, () => {
changes = this._cleanNew(changes);
// Do the update change first so that we can diff against the
// non-updated object.
return this._updateChange(id, changes).then(() => {
return this.table.update(id, changes);
});
});
}
/**
* @param {Object|Collection} query
* @return {Promise<mixed[]>}
*/
_resolveQuery(query) {
return new Promise(resolve => {
if (query instanceof Collection) {
resolve(query.toArray());
} else if (query instanceof Dexie.Promise || query instanceof Promise || isArray(query)) {
resolve(query);
} else {
resolve(this.where(query));
}
});
}
/**
* Method to synchronously return a new object
* suitable for insertion into IndexedDB but
* without actually inserting it
* @param {Object} obj
* @return {Object}
*/
createObj(obj) {
return {
...this._prepareAdd(obj),
[NEW_OBJECT]: true,
};
}
_prepareAdd(obj) {
const idMap = this._prepareCopy({});
return this._cleanNew({
...idMap,
...obj,
});
}
_createChange(id, obj) {
if (!this.syncable) {
return Promise.resolve();
}
const change = new CreatedChange({
key: id,
table: this.tableName,
obj,
source: CLIENTID,
});
return this._saveAndQueueChange(change);
}
/**
* @param {Object} obj
* @return {Promise<string>}
*/
add(obj) {
return this.transaction({ mode: 'rw' }, CHANGES_TABLE, () => {
obj = this._prepareAdd(obj);
return this.table.add(obj).then(id => {
return this._createChange(id, obj).then(() => id);
});
});
}
/**
* @param {Object} original
* @return {Object}
* @private
*/
_prepareCopy(original) {
const id = this.uuid ? { [this.idField]: uuid4() } : {};
return this._cleanNew({
...original,
...id,
});
}
_deleteChange(id) {
if (!this.syncable) {
return Promise.resolve();
}
return this.table.get(id).then(oldObj => {
if (!oldObj) {
return Promise.resolve();
}
const change = new DeletedChange({
key: id,
table: this.tableName,
oldObj,
source: CLIENTID,
});
return this._saveAndQueueChange(change);
});
}
delete(id) {
return this.transaction({ mode: 'rw' }, CHANGES_TABLE, () => {
// Generate delete change first so that we can look up the existing object
return this._deleteChange(id).then(() => {
return this.table.delete(id);
});
});
}
/**
* Return the channel_id for a change, given the object
* @param {Object} obj
* @returns {Object}
*/
getChannelId() {
return;
}
/**
* Return the user_id for a change, given the object
* @param {Object} obj
* @returns {Object}
*/
getUserId() {
return;
}
}
class Resource extends mix(APIResource, IndexedDBResource) {
constructor({ urlName, syncable = true, ...options } = {}) {
super(options);
this.urlName = urlName;
API_RESOURCES[urlName] = this;
// Overwrite the false default for IndexedDBResource
this.syncable = syncable;
// A map of stringified request params to a last fetched time and a promise
this._requests = {};
}
savePagination(queryString, more) {
return this.transaction({ mode: 'rw' }, PAGINATION_TABLE, () => {
// Always save the pagination even if null, so we know we have fetched it
return db[PAGINATION_TABLE].put({ table: this.tableName, queryString, more });
});
}
loadPagination(queryString) {
return db[PAGINATION_TABLE].get([this.tableName, queryString]).then(pagination => {
return pagination ? pagination.more : null;
});
}
fetchCollection(params) {
const now = Date.now();
const queryString = paramsSerializer(params);
const cachedRequest = this._requests[queryString];
if (
cachedRequest &&
cachedRequest[LAST_FETCHED] &&
cachedRequest[LAST_FETCHED] + REFRESH_INTERVAL * 1000 > now &&
cachedRequest.promise
) {
return cachedRequest.promise;
}
const promise = client.get(this.collectionUrl(), { params }).then(response => {
let itemData;
let pageData;
let more;
if (Array.isArray(response.data)) {
itemData = response.data;
} else if (response.data && response.data.results) {
pageData = response.data;
itemData = pageData.results;
more = pageData.more;
} else {
console.error(`Unexpected response from ${this.urlName}`, response);
itemData = [];
}
const paginationPromise = pageData
? this.savePagination(queryString, more)
: Promise.resolve();
return Promise.all([this.setData(itemData), paginationPromise]).then(([data]) => {
// setData also applies any outstanding local change events to the data
// so we return the data returned from setData to make sure the most up to date
// representation is returned from the fetch.
if (pageData) {
pageData.results = data;
}
// If someone has requested a paginated response,
// they will be expecting the page data object,
// not the results object.
return pageData ? pageData : data;
});
});
this._requests[queryString] = {
[LAST_FETCHED]: now,
promise,
};
return promise;
}
conditionalFetch(objs, params, doRefresh) {
if (objs === EMPTY_ARRAY) {
return [];
}
// if there are no objects, and it's also not an empty paginated response (objs.results),
// or we mean to refresh
if ((!objs.length && !objs.results?.length) || doRefresh) {
let refresh = Promise.resolve(true);
// ContentNode tree operations are the troublemakers causing the logic below
if (this.tableName === TABLE_NAMES.CONTENTNODE) {
// Only fetch new updates if we don't have pending changes to ContentNode that
// affect local tree structure
refresh = db[CHANGES_TABLE].where('table')
.equals(TABLE_NAMES.CONTENTNODE)
.filter(c => {
if (!TREE_CHANGE_TYPES.includes(c.type)) {
return false;
}
let parent = c.parent;
if (c.type === CHANGE_TYPES.CREATED) {
parent = c.obj.parent;
}
return (
params.parent === parent ||
params.parent === c.key ||
(params.id__in || []).includes(c.key)
);
})
.count()
.then(pendingCount => pendingCount === 0);
}
const fetch = refresh.then(shouldFetch => {
const emptyResults = isArray(objs) ? [] : { results: [] };
return shouldFetch ? this.fetchCollection(params) : emptyResults;
});
// Be sure to return the fetch promise to relay fetched objects in this condition
if (!objs.length && !objs.results?.length) {
return fetch;
}
}
return objs;
}
/**
* @param {Object} params
* @param {Boolean} [doRefresh=true] -- Whether or not to refresh async from server
* @return {Promise<Object[]>}
*/
where(params = {}, doRefresh = true) {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
/* eslint-disable no-console */
console.groupCollapsed(`Getting data for ${this.tableName} table with params: `, params);
console.trace();
console.groupEnd();
/* eslint-enable */
}
const paginationLoadPromise = params[PAGINATION_FIELD]
? this.loadPagination(paramsSerializer(params))
: Promise.resolve(null);
return Promise.all([super.where(params), paginationLoadPromise]).then(([objs, more]) => {
objs = this.conditionalFetch(objs, params, doRefresh);
if (!isArray(objs) && !objs.more && more) {
objs.more = more;
}
return objs;
});
}
whereLiveQuery(params = {}, doRefresh = true) {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
/* eslint-disable no-console */
console.groupCollapsed(`Getting liveQuery for ${this.tableName} table with params: `, params);
console.trace();
console.groupEnd();
/* eslint-enable */
}
const observable = Dexie.liveQuery(() => super.where(params));
let fetched = false;
observable.subscribe({
next: objs => {
if (!fetched) {
fetched = true;
this.conditionalFetch(objs, params, doRefresh);
}
},
});
return observable;
}
headModel(id) {
// If the resource identified by `id` has just been created, but we haven't verified
// the server has applied the change yet, we skip making the HEAD request for it
return db[CHANGES_TABLE].where('[table+key]')
.equals([this.tableName, id])
.filter(c => CREATION_CHANGE_TYPES.includes(c.type))
.count()
.then(pendingCount => {
if (pendingCount === 0) {
return client.head(this.modelUrl(id));
}
});
}
fetchModel(id) {
return client.get(this.modelUrl(id)).then(response => {
return this.setData([response.data]).then(data => data[0]);
});
}
/**
* @param {String} id
* @param {Boolean} [doRefresh=true] -- Whether or not to refresh async from server
* @return {Promise<{}|null>}
*/
get(id, doRefresh = true) {
if (!isString(id)) {
return Promise.reject('Only string ID format is supported');
}
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
/* eslint-disable no-console */
console.groupCollapsed(`Getting instance for ${this.tableName} table with id: ${id}`);
console.trace();
console.groupEnd();
/* eslint-enable */
}
return this.table.get(id).then(obj => {
if (!obj || doRefresh) {
const request = this.fetchModel(id);
if (!obj) {
return request;
}
}
return obj;
});
}
}
/**
* Resource that allows directly creating through the API,
* rather than through IndexedDB. API must explicitly support this.
*/
class CreateModelResource extends Resource {
createModel(data) {
return client.post(this.collectionUrl(), data).then(response => {
const now = Date.now();
const data = response.data;
data[LAST_FETCHED] = now;
// Directly write to the table, rather than using the add method
// to avoid creating change events that we would sync back to the server.
return this.transaction({ mode: 'rw' }, () => {
return this.table.put(data).then(() => {
return data;
});
});
});
}
}
/**
* Tree resources mixin
*/
export class TreeResource extends Resource {
constructor(...args) {
super(...args);
this._locks = {};