@epam/uui-db 4.8.0-beta.0 → 4.8.2

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/index.js CHANGED
@@ -381,10 +381,10 @@ function __classPrivateFieldIn(state, receiver) {
381
381
  /***/ (function(module, exports, __webpack_require__) {
382
382
 
383
383
  "use strict";
384
-
385
- Object.defineProperty(exports, "__esModule", { value: true });
386
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
387
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
384
+
385
+ Object.defineProperty(exports, "__esModule", { value: true });
386
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
387
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
388
388
 
389
389
 
390
390
  /***/ }),
@@ -397,81 +397,81 @@ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.
397
397
  /***/ (function(module, exports, __webpack_require__) {
398
398
 
399
399
  "use strict";
400
-
401
- Object.defineProperty(exports, "__esModule", { value: true });
402
- exports.Db = void 0;
403
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
404
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
405
- var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
406
- var Db = /** @class */ (function () {
407
- function Db(tables, reusedCache) {
408
- this.tables = tables;
409
- this.viewCache = new Map();
410
- /* Views (cached db projections) */
411
- this.valueAbsent = Symbol("ValueAbsent");
412
- if (reusedCache) {
413
- this.viewCache = new Map(reusedCache);
414
- }
415
- else {
416
- this.viewCache = new Map();
417
- }
418
- }
419
- Db.prototype.update = function (mutate) {
420
- var clone = new this.constructor(this.tables, this.viewCache);
421
- clone.tables = (0, tslib_1.__assign)({}, this.tables);
422
- mutate(clone);
423
- return clone;
424
- };
425
- Db.prototype.with = function (patch) {
426
- return this.update(function (db) {
427
- (0, utils_1.objectKeys)(db.tables).forEach(function (entityName) {
428
- if (patch[entityName]) {
429
- db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
430
- }
431
- });
432
- });
433
- };
434
- Db.prototype.runView = function (view, params) {
435
- var cache = this.viewCache.get(view);
436
- if (!cache) {
437
- cache = new Map();
438
- this.viewCache.set(view, cache);
439
- }
440
- var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
441
- var cacheItem = cache.get(key);
442
- if (!cacheItem) {
443
- cacheItem = {
444
- dependencies: this.valueAbsent,
445
- currentValue: this.valueAbsent,
446
- computedOnDb: this.valueAbsent,
447
- };
448
- cache.set(key, cacheItem);
449
- }
450
- var shouldUpdate = this !== cacheItem.computedOnDb;
451
- var dependencies = this.valueAbsent;
452
- if (view.getDependencies) {
453
- var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
454
- dependencies = view.getDependencies(this, params);
455
- shouldUpdate = !compare(cacheItem.dependencies, dependencies);
456
- }
457
- var previousValue = cacheItem.currentValue;
458
- if (shouldUpdate) {
459
- cacheItem.dependencies = dependencies;
460
- var newValue = view.compute(this, params, dependencies);
461
- cacheItem.computedOnDb = this;
462
- var compareResults = view.compareResults || lodash_isequal_1.default;
463
- if (!compareResults(previousValue, newValue)) {
464
- if (view.traceDiff) {
465
- console.debug((0, utils_1.difference)(previousValue, newValue));
466
- }
467
- cacheItem.currentValue = newValue;
468
- }
469
- }
470
- return cacheItem.currentValue;
471
- };
472
- return Db;
473
- }());
474
- exports.Db = Db;
400
+
401
+ Object.defineProperty(exports, "__esModule", { value: true });
402
+ exports.Db = void 0;
403
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
404
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
405
+ var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
406
+ var Db = /** @class */ (function () {
407
+ function Db(tables, reusedCache) {
408
+ this.tables = tables;
409
+ this.viewCache = new Map();
410
+ /* Views (cached db projections) */
411
+ this.valueAbsent = Symbol("ValueAbsent");
412
+ if (reusedCache) {
413
+ this.viewCache = new Map(reusedCache);
414
+ }
415
+ else {
416
+ this.viewCache = new Map();
417
+ }
418
+ }
419
+ Db.prototype.update = function (mutate) {
420
+ var clone = new this.constructor(this.tables, this.viewCache);
421
+ clone.tables = (0, tslib_1.__assign)({}, this.tables);
422
+ mutate(clone);
423
+ return clone;
424
+ };
425
+ Db.prototype.with = function (patch) {
426
+ return this.update(function (db) {
427
+ (0, utils_1.objectKeys)(db.tables).forEach(function (entityName) {
428
+ if (patch[entityName]) {
429
+ db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
430
+ }
431
+ });
432
+ });
433
+ };
434
+ Db.prototype.runView = function (view, params) {
435
+ var cache = this.viewCache.get(view);
436
+ if (!cache) {
437
+ cache = new Map();
438
+ this.viewCache.set(view, cache);
439
+ }
440
+ var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
441
+ var cacheItem = cache.get(key);
442
+ if (!cacheItem) {
443
+ cacheItem = {
444
+ dependencies: this.valueAbsent,
445
+ currentValue: this.valueAbsent,
446
+ computedOnDb: this.valueAbsent,
447
+ };
448
+ cache.set(key, cacheItem);
449
+ }
450
+ var shouldUpdate = this !== cacheItem.computedOnDb;
451
+ var dependencies = this.valueAbsent;
452
+ if (view.getDependencies) {
453
+ var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
454
+ dependencies = view.getDependencies(this, params);
455
+ shouldUpdate = !compare(cacheItem.dependencies, dependencies);
456
+ }
457
+ var previousValue = cacheItem.currentValue;
458
+ if (shouldUpdate) {
459
+ cacheItem.dependencies = dependencies;
460
+ var newValue = view.compute(this, params, dependencies);
461
+ cacheItem.computedOnDb = this;
462
+ var compareResults = view.compareResults || lodash_isequal_1.default;
463
+ if (!compareResults(previousValue, newValue)) {
464
+ if (view.traceDiff) {
465
+ console.debug((0, utils_1.difference)(previousValue, newValue));
466
+ }
467
+ cacheItem.currentValue = newValue;
468
+ }
469
+ }
470
+ return cacheItem.currentValue;
471
+ };
472
+ return Db;
473
+ }());
474
+ exports.Db = Db;
475
475
 
476
476
 
477
477
  /***/ }),
@@ -484,213 +484,213 @@ exports.Db = Db;
484
484
  /***/ (function(module, exports, __webpack_require__) {
485
485
 
486
486
  "use strict";
487
-
488
- Object.defineProperty(exports, "__esModule", { value: true });
489
- exports.DbRef = void 0;
490
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
491
- var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
492
- var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
493
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
494
- var lodash_isempty_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
495
- var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
496
- var uui_core_1 = __webpack_require__(/*! @epam/uui-core */ "@epam/uui-core");
497
- var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
498
- var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
499
- var DbRef = /** @class */ (function () {
500
- function DbRef(blank) {
501
- var _this = this;
502
- this.blank = blank;
503
- this.log = [];
504
- this.autoSave = true;
505
- this.savedPoint = 0;
506
- this.throttleSaveMs = 1000;
507
- /* Update subscriptions (aka live views) */
508
- this.lastSubscriptionId = 1;
509
- this.subscriptions = new Map();
510
- this.updateHandlers = [];
511
- /* Error Subscriptions */
512
- this.saveErrorHandlers = [];
513
- /* Save scheduling */
514
- this.enqueueSave = (0, uui_core_1.batch)(function () { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
515
- var cumulativePatch, lastLogEntry, response, error_1;
516
- return (0, tslib_1.__generator)(this, function (_a) {
517
- switch (_a.label) {
518
- case 0:
519
- cumulativePatch = this.makeCumulativePatch();
520
- lastLogEntry = this.log.length;
521
- if ((0, lodash_isempty_1.default)(cumulativePatch)) {
522
- return [2 /*return*/];
523
- }
524
- _a.label = 1;
525
- case 1:
526
- _a.trys.push([1, 3, , 4]);
527
- return [4 /*yield*/, this.savePatch(cumulativePatch)];
528
- case 2:
529
- response = _a.sent();
530
- this.applyResponse(response, lastLogEntry);
531
- this.update();
532
- return [3 /*break*/, 4];
533
- case 3:
534
- error_1 = _a.sent();
535
- this.saveError(cumulativePatch, error_1);
536
- this.update();
537
- throw error_1;
538
- case 4: return [2 /*return*/];
539
- }
540
- });
541
- }); });
542
- this.handleBeforeUnload = function (e) {
543
- if (_this.enqueueSave.isBusy) {
544
- e.returnValue = false;
545
- return false;
546
- }
547
- };
548
- this.loaders = [];
549
- this.db = blank;
550
- this.base = blank;
551
- this.tempIdMap = new tempIds_1.TempIdMap(blank);
552
- this.idMap = this.tempIdMap;
553
- window.addEventListener('beforeunload', this.handleBeforeUnload);
554
- }
555
- /** Saves all committed patches. Useful only if autoSave is off. */
556
- DbRef.prototype.save = function () {
557
- return this.enqueueSave();
558
- };
559
- DbRef.prototype.getAutoSave = function () {
560
- return this.autoSave;
561
- };
562
- DbRef.prototype.setAutoSave = function (val) {
563
- if (this.autoSave != val) {
564
- this.autoSave = val;
565
- this.autoSave && this.enqueueSave();
566
- this.update();
567
- }
568
- };
569
- DbRef.prototype.revert = function () {
570
- this.db = this.base;
571
- this.log = this.log.slice(0, this.savedPoint);
572
- this.update();
573
- };
574
- /** Concrete DbRef instances should override and implement their save logic in this method */
575
- DbRef.prototype.savePatch = function (patch) {
576
- return Promise.resolve({ submit: {} });
577
- };
578
- /* Db Update logic */
579
- DbRef.prototype.commit = function (patch) {
580
- var dbBeforeUpdate = this.db.with(patch);
581
- patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
582
- patch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, patch);
583
- this.log.push({ patch: patch });
584
- this.db = this.db.with(patch);
585
- this.autoSave && this.enqueueSave(null, { throttleMs: this.throttleSaveMs });
586
- this.update();
587
- };
588
- DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
589
- var _this = this;
590
- var patchAndDependencies = {};
591
- (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
592
- patchAndDependencies[entityName] = patch[entityName];
593
- });
594
- (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
595
- var _a;
596
- var schema = tables[entityName].schema;
597
- var beforeUpdate = schema.beforeUpdate;
598
- var context = {
599
- clientIdsMap: _this.tempIdMap,
600
- schema: schema,
601
- tables: tables,
602
- prevTables: prevTables,
603
- };
604
- var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
605
- var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
606
- var dependentEntityPatchesForUpdate = (0, patchHelpers_1.unionPatches)(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
607
- var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
608
- patchAndDependencies = (0, patchHelpers_1.mergeEntityPatches)(tables, (0, patchHelpers_1.unionPatches)([patchAndDependencies, updatedPatch, dependentEntityPatches]));
609
- });
610
- return patchAndDependencies;
611
- };
612
- DbRef.prototype.commitFetch = function (patch) {
613
- patch = this.tempIdMap.serverToClientPatch(patch);
614
- this.rebase(this.base.with(patch));
615
- this.update();
616
- };
617
- DbRef.prototype.rebase = function (newBase) {
618
- this.base = newBase;
619
- this.db = newBase;
620
- for (var n = this.savedPoint; n < this.log.length; n++) {
621
- this.db = this.db.with(this.log[n].patch);
622
- }
623
- };
624
- DbRef.prototype.makeCumulativePatch = function () {
625
- var lastLogEntry = this.log.length;
626
- var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
627
- var cumulativePatch = (0, patchHelpers_1.makeCumulativePatch)(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
628
- cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
629
- return cumulativePatch;
630
- };
631
- DbRef.prototype.applyResponse = function (response, newSavedPoint) {
632
- this.tempIdMap.appendServerMapping(response);
633
- var serverPatch = (0, patchHelpers_1.flattenResponse)(response.submit, this.db.tables);
634
- serverPatch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, serverPatch);
635
- this.savedPoint = newSavedPoint;
636
- this.base = this.db;
637
- this.commitFetch(serverPatch);
638
- };
639
- DbRef.prototype.subscribe = function (view, params, onUpdate) {
640
- var _this = this;
641
- var id = this.lastSubscriptionId++;
642
- var subscription = {
643
- update: function (params) {
644
- subscription.currentParams = params;
645
- subscription.currentValue = _this.db.runView(view, params);
646
- return subscription.currentValue;
647
- },
648
- currentParams: null,
649
- currentValue: null,
650
- onUpdate: onUpdate,
651
- unsubscribe: function () { _this.subscriptions.delete(id); },
652
- };
653
- subscription.update(params);
654
- this.subscriptions.set(id, subscription);
655
- return subscription;
656
- };
657
- DbRef.prototype.onUpdate = function (handler) {
658
- this.subscribe({
659
- compute: function (db) { return db; },
660
- compareResults: function (a, b) { return a === b; },
661
- }, null, handler);
662
- };
663
- DbRef.prototype.update = function () {
664
- this.subscriptions.forEach(function (subscription) {
665
- var previousValue = subscription.currentValue;
666
- subscription.update(subscription.currentParams);
667
- if (subscription.currentValue !== previousValue && subscription.onUpdate) {
668
- subscription.onUpdate(subscription.currentValue);
669
- }
670
- });
671
- };
672
- DbRef.prototype.onSaveError = function (handler) {
673
- this.saveErrorHandlers.push(handler);
674
- };
675
- DbRef.prototype.saveError = function (request, error) {
676
- this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
677
- };
678
- DbRef.prototype.makeLoader = function (options) {
679
- var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
680
- this.loaders.push(loader);
681
- return loader;
682
- };
683
- DbRef.prototype.makeListLoader = function (options) {
684
- var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
685
- this.loaders.push(loader);
686
- return loader;
687
- };
688
- DbRef.prototype.reload = function () {
689
- this.loaders = [];
690
- };
691
- return DbRef;
692
- }());
693
- exports.DbRef = DbRef;
487
+
488
+ Object.defineProperty(exports, "__esModule", { value: true });
489
+ exports.DbRef = void 0;
490
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
491
+ var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
492
+ var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
493
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
494
+ var lodash_isempty_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
495
+ var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
496
+ var uui_core_1 = __webpack_require__(/*! @epam/uui-core */ "@epam/uui-core");
497
+ var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
498
+ var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
499
+ var DbRef = /** @class */ (function () {
500
+ function DbRef(blank) {
501
+ var _this = this;
502
+ this.blank = blank;
503
+ this.log = [];
504
+ this.autoSave = true;
505
+ this.savedPoint = 0;
506
+ this.throttleSaveMs = 1000;
507
+ /* Update subscriptions (aka live views) */
508
+ this.lastSubscriptionId = 1;
509
+ this.subscriptions = new Map();
510
+ this.updateHandlers = [];
511
+ /* Error Subscriptions */
512
+ this.saveErrorHandlers = [];
513
+ /* Save scheduling */
514
+ this.enqueueSave = (0, uui_core_1.batch)(function () { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
515
+ var cumulativePatch, lastLogEntry, response, error_1;
516
+ return (0, tslib_1.__generator)(this, function (_a) {
517
+ switch (_a.label) {
518
+ case 0:
519
+ cumulativePatch = this.makeCumulativePatch();
520
+ lastLogEntry = this.log.length;
521
+ if ((0, lodash_isempty_1.default)(cumulativePatch)) {
522
+ return [2 /*return*/];
523
+ }
524
+ _a.label = 1;
525
+ case 1:
526
+ _a.trys.push([1, 3, , 4]);
527
+ return [4 /*yield*/, this.savePatch(cumulativePatch)];
528
+ case 2:
529
+ response = _a.sent();
530
+ this.applyResponse(response, lastLogEntry);
531
+ this.update();
532
+ return [3 /*break*/, 4];
533
+ case 3:
534
+ error_1 = _a.sent();
535
+ this.saveError(cumulativePatch, error_1);
536
+ this.update();
537
+ throw error_1;
538
+ case 4: return [2 /*return*/];
539
+ }
540
+ });
541
+ }); });
542
+ this.handleBeforeUnload = function (e) {
543
+ if (_this.enqueueSave.isBusy) {
544
+ e.returnValue = false;
545
+ return false;
546
+ }
547
+ };
548
+ this.loaders = [];
549
+ this.db = blank;
550
+ this.base = blank;
551
+ this.tempIdMap = new tempIds_1.TempIdMap(blank);
552
+ this.idMap = this.tempIdMap;
553
+ window.addEventListener('beforeunload', this.handleBeforeUnload);
554
+ }
555
+ /** Saves all committed patches. Useful only if autoSave is off. */
556
+ DbRef.prototype.save = function () {
557
+ return this.enqueueSave();
558
+ };
559
+ DbRef.prototype.getAutoSave = function () {
560
+ return this.autoSave;
561
+ };
562
+ DbRef.prototype.setAutoSave = function (val) {
563
+ if (this.autoSave != val) {
564
+ this.autoSave = val;
565
+ this.autoSave && this.enqueueSave();
566
+ this.update();
567
+ }
568
+ };
569
+ DbRef.prototype.revert = function () {
570
+ this.db = this.base;
571
+ this.log = this.log.slice(0, this.savedPoint);
572
+ this.update();
573
+ };
574
+ /** Concrete DbRef instances should override and implement their save logic in this method */
575
+ DbRef.prototype.savePatch = function (patch) {
576
+ return Promise.resolve({ submit: {} });
577
+ };
578
+ /* Db Update logic */
579
+ DbRef.prototype.commit = function (patch) {
580
+ var dbBeforeUpdate = this.db.with(patch);
581
+ patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
582
+ patch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, patch);
583
+ this.log.push({ patch: patch });
584
+ this.db = this.db.with(patch);
585
+ this.autoSave && this.enqueueSave(null, { throttleMs: this.throttleSaveMs });
586
+ this.update();
587
+ };
588
+ DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
589
+ var _this = this;
590
+ var patchAndDependencies = {};
591
+ (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
592
+ patchAndDependencies[entityName] = patch[entityName];
593
+ });
594
+ (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
595
+ var _a;
596
+ var schema = tables[entityName].schema;
597
+ var beforeUpdate = schema.beforeUpdate;
598
+ var context = {
599
+ clientIdsMap: _this.tempIdMap,
600
+ schema: schema,
601
+ tables: tables,
602
+ prevTables: prevTables,
603
+ };
604
+ var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
605
+ var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
606
+ var dependentEntityPatchesForUpdate = (0, patchHelpers_1.unionPatches)(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
607
+ var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
608
+ patchAndDependencies = (0, patchHelpers_1.mergeEntityPatches)(tables, (0, patchHelpers_1.unionPatches)([patchAndDependencies, updatedPatch, dependentEntityPatches]));
609
+ });
610
+ return patchAndDependencies;
611
+ };
612
+ DbRef.prototype.commitFetch = function (patch) {
613
+ patch = this.tempIdMap.serverToClientPatch(patch);
614
+ this.rebase(this.base.with(patch));
615
+ this.update();
616
+ };
617
+ DbRef.prototype.rebase = function (newBase) {
618
+ this.base = newBase;
619
+ this.db = newBase;
620
+ for (var n = this.savedPoint; n < this.log.length; n++) {
621
+ this.db = this.db.with(this.log[n].patch);
622
+ }
623
+ };
624
+ DbRef.prototype.makeCumulativePatch = function () {
625
+ var lastLogEntry = this.log.length;
626
+ var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
627
+ var cumulativePatch = (0, patchHelpers_1.makeCumulativePatch)(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
628
+ cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
629
+ return cumulativePatch;
630
+ };
631
+ DbRef.prototype.applyResponse = function (response, newSavedPoint) {
632
+ this.tempIdMap.appendServerMapping(response);
633
+ var serverPatch = (0, patchHelpers_1.flattenResponse)(response.submit, this.db.tables);
634
+ serverPatch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, serverPatch);
635
+ this.savedPoint = newSavedPoint;
636
+ this.base = this.db;
637
+ this.commitFetch(serverPatch);
638
+ };
639
+ DbRef.prototype.subscribe = function (view, params, onUpdate) {
640
+ var _this = this;
641
+ var id = this.lastSubscriptionId++;
642
+ var subscription = {
643
+ update: function (params) {
644
+ subscription.currentParams = params;
645
+ subscription.currentValue = _this.db.runView(view, params);
646
+ return subscription.currentValue;
647
+ },
648
+ currentParams: null,
649
+ currentValue: null,
650
+ onUpdate: onUpdate,
651
+ unsubscribe: function () { _this.subscriptions.delete(id); },
652
+ };
653
+ subscription.update(params);
654
+ this.subscriptions.set(id, subscription);
655
+ return subscription;
656
+ };
657
+ DbRef.prototype.onUpdate = function (handler) {
658
+ this.subscribe({
659
+ compute: function (db) { return db; },
660
+ compareResults: function (a, b) { return a === b; },
661
+ }, null, handler);
662
+ };
663
+ DbRef.prototype.update = function () {
664
+ this.subscriptions.forEach(function (subscription) {
665
+ var previousValue = subscription.currentValue;
666
+ subscription.update(subscription.currentParams);
667
+ if (subscription.currentValue !== previousValue && subscription.onUpdate) {
668
+ subscription.onUpdate(subscription.currentValue);
669
+ }
670
+ });
671
+ };
672
+ DbRef.prototype.onSaveError = function (handler) {
673
+ this.saveErrorHandlers.push(handler);
674
+ };
675
+ DbRef.prototype.saveError = function (request, error) {
676
+ this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
677
+ };
678
+ DbRef.prototype.makeLoader = function (options) {
679
+ var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
680
+ this.loaders.push(loader);
681
+ return loader;
682
+ };
683
+ DbRef.prototype.makeListLoader = function (options) {
684
+ var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
685
+ this.loaders.push(loader);
686
+ return loader;
687
+ };
688
+ DbRef.prototype.reload = function () {
689
+ this.loaders = [];
690
+ };
691
+ return DbRef;
692
+ }());
693
+ exports.DbRef = DbRef;
694
694
 
695
695
 
696
696
  /***/ }),
@@ -703,219 +703,219 @@ exports.DbRef = DbRef;
703
703
  /***/ (function(module, exports, __webpack_require__) {
704
704
 
705
705
  "use strict";
706
-
707
- Object.defineProperty(exports, "__esModule", { value: true });
708
- exports.DbTable = void 0;
709
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
710
- var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
711
- var uui_core_1 = __webpack_require__(/*! @epam/uui-core */ "@epam/uui-core");
712
- var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
713
- var DbTable = /** @class */ (function () {
714
- function DbTable(schema, state, q) {
715
- this.schema = schema;
716
- this.state = state;
717
- this.q = q;
718
- if (!state) {
719
- var indexes = (schema.indexes || []).map(function (indexDef) {
720
- return {
721
- field: indexDef,
722
- map: I.Map(),
723
- };
724
- });
725
- this.state = { pk: I.Map(), indexes: indexes };
726
- }
727
- if (!q) {
728
- this.q = {};
729
- }
730
- }
731
- DbTable.prototype.keyToImmutable = function (id) {
732
- if (Array.isArray(id)) {
733
- return I.List(id);
734
- }
735
- else {
736
- return id;
737
- }
738
- };
739
- DbTable.prototype.byId = function (id) {
740
- return this.state.pk.get(this.keyToImmutable(id));
741
- };
742
- DbTable.prototype.getId = function (entity) {
743
- if (Array.isArray(this.schema.primaryKey)) {
744
- return this.schema.primaryKey.map(function (key) { return entity[key]; });
745
- }
746
- return entity[this.schema.primaryKey];
747
- };
748
- DbTable.prototype.update = function (mutate) {
749
- var clone = new this.constructor(this.schema, this.state, this.q);
750
- mutate(clone);
751
- return clone;
752
- };
753
- /* Mutation */
754
- DbTable.prototype.with = function (patch) {
755
- var _this = this;
756
- var updates = patch.map(function (entityPatch) {
757
- var id = _this.getId(entityPatch);
758
- var immId = _this.keyToImmutable(id);
759
- var existing = _this.state.pk.get(immId);
760
- var isDeleted = false;
761
- var updated = entityPatch;
762
- if (existing) {
763
- updated = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, existing), entityPatch);
764
- if (_this.schema.deleteFlag) {
765
- isDeleted = updated[_this.schema.deleteFlag] === true;
766
- }
767
- }
768
- return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, isNew: !existing, isDeleted: isDeleted };
769
- });
770
- var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
771
- var newPk = this.state.pk.merge(idVal);
772
- // TBD: replace with deleteAll after migrating to immutable 4
773
- updates.filter(function (u) { return u.isDeleted; }).forEach(function (u) {
774
- newPk = newPk.delete(u.immId);
775
- });
776
- var newIndexes = this.state.indexes.map(function (index) {
777
- var newMap = index.map;
778
- var _loop_1 = function (n) {
779
- var update = updates[n];
780
- var newKey = update.updated[index.field];
781
- if (update.existing) {
782
- var oldKey = update.existing[index.field];
783
- if (oldKey !== newKey || update.isDeleted) {
784
- newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
785
- }
786
- }
787
- if (!update.isDeleted) {
788
- newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
789
- }
790
- };
791
- for (var n = 0; n < updates.length; n++) {
792
- _loop_1(n);
793
- }
794
- return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, index), { map: newMap });
795
- });
796
- var newState = { pk: newPk, indexes: newIndexes };
797
- return this.update(function (t) { return t.state = newState; });
798
- };
799
- /* Query */
800
- DbTable.prototype.find = function (filter) {
801
- var _this = this;
802
- return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { filter: (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _this.q.filter), filter) }); });
803
- };
804
- DbTable.prototype.order = function (order) {
805
- return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: order }); });
806
- };
807
- DbTable.prototype.orderBy = function (field, direction) {
808
- if (direction === void 0) { direction = 'asc'; }
809
- return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
810
- };
811
- DbTable.prototype.thenBy = function (field, direction) {
812
- return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], t.q.sorting, true), [{ field: field, direction: direction }], false) }); });
813
- };
814
- DbTable.prototype.search = function (text) {
815
- if (!this.schema.searchBy) {
816
- throw new Error("Can't search in the ".concat(this.schema.typeName, " table - searchBy is not defined in the schema."));
817
- }
818
- return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { search: text }); });
819
- };
820
- /* Materializing */
821
- DbTable.prototype.range = function (from, count) {
822
- return this.runQuery((0, tslib_1.__assign)((0, tslib_1.__assign)({}, this.q), { range: { from: from, count: count } }));
823
- };
824
- DbTable.prototype.count = function () {
825
- return this.runQuery(this.q).length;
826
- };
827
- DbTable.prototype.one = function () {
828
- return this.runQuery(this.q)[0] || null;
829
- };
830
- DbTable.prototype.toArray = function () {
831
- return this.runQuery(this.q);
832
- };
833
- DbTable.prototype.map = function (fn) {
834
- return this.toArray().map(fn);
835
- };
836
- /* Query implementation */
837
- DbTable.prototype.runQuery = function (q) {
838
- var _this = this;
839
- var result = null;
840
- var filter = q.filter;
841
- if (filter) {
842
- var indexes = this.state.indexes;
843
- // Try to use indexes to fulfill filter conditions
844
- for (var n = 0; n < indexes.length; n++) {
845
- var index = indexes[n];
846
- if (index.field in filter) {
847
- var _a = filter, _b = index.field, condition = _a[_b], rest = (0, tslib_1.__rest)(_a, [typeof _b === "symbol" ? _b : _b + ""]);
848
- var conditionValues = null;
849
- if (condition != null && typeof condition === "object") {
850
- // Attempt to use index for 'in' and 'isNull' criteria.
851
- // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
852
- // - it's better to leave corner cases to getPatternPredicate
853
- var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = (0, tslib_1.__rest)(_c, ["in", "isNull"]);
854
- if (inCriteria && Array.isArray(inCriteria)) {
855
- conditionValues = inCriteria;
856
- }
857
- else {
858
- restCriteria.in = inCriteria;
859
- }
860
- // Conditions in getPatternPredicate are composed with 'and' logic,
861
- // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
862
- // - just leave this to getPatternPredicate.
863
- // Let's just handle the a most common case { isNull: true } - find all null and undefined
864
- if (nullCriteria === true && !conditionValues) {
865
- conditionValues = [null, undefined];
866
- }
867
- else {
868
- restCriteria.in = inCriteria;
869
- }
870
- // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
871
- if (Object.keys(restCriteria).length > 0) {
872
- rest[index.field] = restCriteria;
873
- }
874
- }
875
- else {
876
- conditionValues = [condition];
877
- }
878
- if (conditionValues) {
879
- result = [];
880
- for (var i = 0; i < conditionValues.length; i++) {
881
- var idsSet = index.map.get(conditionValues[i]);
882
- if (idsSet) {
883
- var idsArray = idsSet.toArray();
884
- for (var j = 0; j < idsArray.length; j++) {
885
- var item = this.state.pk.get(idsArray[j]);
886
- result.push(item);
887
- }
888
- }
889
- }
890
- filter = Object.keys(rest).length > 0 ? rest : null;
891
- break;
892
- }
893
- }
894
- }
895
- }
896
- if (!result) {
897
- result = this.state.pk.toArray();
898
- }
899
- if (filter) {
900
- var predicate = (0, uui_core_1.getPatternPredicate)(q.filter);
901
- result = result.filter(predicate);
902
- }
903
- if (q.search) {
904
- var searchFilter_1 = (0, uui_core_1.getSearchFilter)(q.search);
905
- result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
906
- }
907
- if (q.sorting) {
908
- var comparer = (0, uui_core_1.getOrderComparer)(q.sorting);
909
- result = result.sort(comparer);
910
- }
911
- if (q.range) {
912
- result = result.slice(q.range.from, q.range.from + q.range.count);
913
- }
914
- return result;
915
- };
916
- return DbTable;
917
- }());
918
- exports.DbTable = DbTable;
706
+
707
+ Object.defineProperty(exports, "__esModule", { value: true });
708
+ exports.DbTable = void 0;
709
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
710
+ var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
711
+ var uui_core_1 = __webpack_require__(/*! @epam/uui-core */ "@epam/uui-core");
712
+ var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
713
+ var DbTable = /** @class */ (function () {
714
+ function DbTable(schema, state, q) {
715
+ this.schema = schema;
716
+ this.state = state;
717
+ this.q = q;
718
+ if (!state) {
719
+ var indexes = (schema.indexes || []).map(function (indexDef) {
720
+ return {
721
+ field: indexDef,
722
+ map: I.Map(),
723
+ };
724
+ });
725
+ this.state = { pk: I.Map(), indexes: indexes };
726
+ }
727
+ if (!q) {
728
+ this.q = {};
729
+ }
730
+ }
731
+ DbTable.prototype.keyToImmutable = function (id) {
732
+ if (Array.isArray(id)) {
733
+ return I.List(id);
734
+ }
735
+ else {
736
+ return id;
737
+ }
738
+ };
739
+ DbTable.prototype.byId = function (id) {
740
+ return this.state.pk.get(this.keyToImmutable(id));
741
+ };
742
+ DbTable.prototype.getId = function (entity) {
743
+ if (Array.isArray(this.schema.primaryKey)) {
744
+ return this.schema.primaryKey.map(function (key) { return entity[key]; });
745
+ }
746
+ return entity[this.schema.primaryKey];
747
+ };
748
+ DbTable.prototype.update = function (mutate) {
749
+ var clone = new this.constructor(this.schema, this.state, this.q);
750
+ mutate(clone);
751
+ return clone;
752
+ };
753
+ /* Mutation */
754
+ DbTable.prototype.with = function (patch) {
755
+ var _this = this;
756
+ var updates = patch.map(function (entityPatch) {
757
+ var id = _this.getId(entityPatch);
758
+ var immId = _this.keyToImmutable(id);
759
+ var existing = _this.state.pk.get(immId);
760
+ var isDeleted = false;
761
+ var updated = entityPatch;
762
+ if (existing) {
763
+ updated = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, existing), entityPatch);
764
+ if (_this.schema.deleteFlag) {
765
+ isDeleted = updated[_this.schema.deleteFlag] === true;
766
+ }
767
+ }
768
+ return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, isNew: !existing, isDeleted: isDeleted };
769
+ });
770
+ var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
771
+ var newPk = this.state.pk.merge(idVal);
772
+ // TBD: replace with deleteAll after migrating to immutable 4
773
+ updates.filter(function (u) { return u.isDeleted; }).forEach(function (u) {
774
+ newPk = newPk.delete(u.immId);
775
+ });
776
+ var newIndexes = this.state.indexes.map(function (index) {
777
+ var newMap = index.map;
778
+ var _loop_1 = function (n) {
779
+ var update = updates[n];
780
+ var newKey = update.updated[index.field];
781
+ if (update.existing) {
782
+ var oldKey = update.existing[index.field];
783
+ if (oldKey !== newKey || update.isDeleted) {
784
+ newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
785
+ }
786
+ }
787
+ if (!update.isDeleted) {
788
+ newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
789
+ }
790
+ };
791
+ for (var n = 0; n < updates.length; n++) {
792
+ _loop_1(n);
793
+ }
794
+ return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, index), { map: newMap });
795
+ });
796
+ var newState = { pk: newPk, indexes: newIndexes };
797
+ return this.update(function (t) { return t.state = newState; });
798
+ };
799
+ /* Query */
800
+ DbTable.prototype.find = function (filter) {
801
+ var _this = this;
802
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { filter: (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _this.q.filter), filter) }); });
803
+ };
804
+ DbTable.prototype.order = function (order) {
805
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: order }); });
806
+ };
807
+ DbTable.prototype.orderBy = function (field, direction) {
808
+ if (direction === void 0) { direction = 'asc'; }
809
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
810
+ };
811
+ DbTable.prototype.thenBy = function (field, direction) {
812
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], t.q.sorting, true), [{ field: field, direction: direction }], false) }); });
813
+ };
814
+ DbTable.prototype.search = function (text) {
815
+ if (!this.schema.searchBy) {
816
+ throw new Error("Can't search in the ".concat(this.schema.typeName, " table - searchBy is not defined in the schema."));
817
+ }
818
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { search: text }); });
819
+ };
820
+ /* Materializing */
821
+ DbTable.prototype.range = function (from, count) {
822
+ return this.runQuery((0, tslib_1.__assign)((0, tslib_1.__assign)({}, this.q), { range: { from: from, count: count } }));
823
+ };
824
+ DbTable.prototype.count = function () {
825
+ return this.runQuery(this.q).length;
826
+ };
827
+ DbTable.prototype.one = function () {
828
+ return this.runQuery(this.q)[0] || null;
829
+ };
830
+ DbTable.prototype.toArray = function () {
831
+ return this.runQuery(this.q);
832
+ };
833
+ DbTable.prototype.map = function (fn) {
834
+ return this.toArray().map(fn);
835
+ };
836
+ /* Query implementation */
837
+ DbTable.prototype.runQuery = function (q) {
838
+ var _this = this;
839
+ var result = null;
840
+ var filter = q.filter;
841
+ if (filter) {
842
+ var indexes = this.state.indexes;
843
+ // Try to use indexes to fulfill filter conditions
844
+ for (var n = 0; n < indexes.length; n++) {
845
+ var index = indexes[n];
846
+ if (index.field in filter) {
847
+ var _a = filter, _b = index.field, condition = _a[_b], rest = (0, tslib_1.__rest)(_a, [typeof _b === "symbol" ? _b : _b + ""]);
848
+ var conditionValues = null;
849
+ if (condition != null && typeof condition === "object") {
850
+ // Attempt to use index for 'in' and 'isNull' criteria.
851
+ // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
852
+ // - it's better to leave corner cases to getPatternPredicate
853
+ var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = (0, tslib_1.__rest)(_c, ["in", "isNull"]);
854
+ if (inCriteria && Array.isArray(inCriteria)) {
855
+ conditionValues = inCriteria;
856
+ }
857
+ else {
858
+ restCriteria.in = inCriteria;
859
+ }
860
+ // Conditions in getPatternPredicate are composed with 'and' logic,
861
+ // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
862
+ // - just leave this to getPatternPredicate.
863
+ // Let's just handle the a most common case { isNull: true } - find all null and undefined
864
+ if (nullCriteria === true && !conditionValues) {
865
+ conditionValues = [null, undefined];
866
+ }
867
+ else {
868
+ restCriteria.in = inCriteria;
869
+ }
870
+ // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
871
+ if (Object.keys(restCriteria).length > 0) {
872
+ rest[index.field] = restCriteria;
873
+ }
874
+ }
875
+ else {
876
+ conditionValues = [condition];
877
+ }
878
+ if (conditionValues) {
879
+ result = [];
880
+ for (var i = 0; i < conditionValues.length; i++) {
881
+ var idsSet = index.map.get(conditionValues[i]);
882
+ if (idsSet) {
883
+ var idsArray = idsSet.toArray();
884
+ for (var j = 0; j < idsArray.length; j++) {
885
+ var item = this.state.pk.get(idsArray[j]);
886
+ result.push(item);
887
+ }
888
+ }
889
+ }
890
+ filter = Object.keys(rest).length > 0 ? rest : null;
891
+ break;
892
+ }
893
+ }
894
+ }
895
+ }
896
+ if (!result) {
897
+ result = this.state.pk.toArray();
898
+ }
899
+ if (filter) {
900
+ var predicate = (0, uui_core_1.getFilterPredicate)(q.filter);
901
+ result = result.filter(predicate);
902
+ }
903
+ if (q.search) {
904
+ var searchFilter_1 = (0, uui_core_1.getSearchFilter)(q.search);
905
+ result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
906
+ }
907
+ if (q.sorting) {
908
+ var comparer = (0, uui_core_1.getOrderComparer)(q.sorting);
909
+ result = result.sort(comparer);
910
+ }
911
+ if (q.range) {
912
+ result = result.slice(q.range.from, q.range.from + q.range.count);
913
+ }
914
+ return result;
915
+ };
916
+ return DbTable;
917
+ }());
918
+ exports.DbTable = DbTable;
919
919
 
920
920
 
921
921
  /***/ }),
@@ -928,99 +928,99 @@ exports.DbTable = DbTable;
928
928
  /***/ (function(module, exports, __webpack_require__) {
929
929
 
930
930
  "use strict";
931
-
932
- Object.defineProperty(exports, "__esModule", { value: true });
933
- exports.ListLoadingTracker = void 0;
934
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
935
- var ListLoadingTracker = /** @class */ (function () {
936
- function ListLoadingTracker(options) {
937
- this.options = options;
938
- this.cache = new Map();
939
- this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
940
- }
941
- ListLoadingTracker.prototype.prepare = function (request) {
942
- var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = (0, tslib_1.__rest)(request, ["filter", "sorting", "search", "range"]);
943
- var options = {};
944
- if (filter) {
945
- options.filter = filter;
946
- }
947
- if (sorting) {
948
- options.sorting = sorting;
949
- }
950
- if (search) {
951
- options.search = search;
952
- }
953
- var keyObject = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields);
954
- var key = JSON.stringify(keyObject);
955
- var entry = this.cache.get(key);
956
- if (!entry) {
957
- entry = { options: options, count: 0, maxCount: null, isComplete: false };
958
- this.cache.set(key, entry);
959
- }
960
- return { options: options, range: range, unknownFields: unknownFields, entry: entry };
961
- };
962
- ListLoadingTracker.prototype.diff = function (request) {
963
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
964
- if (entry.isComplete) {
965
- return null;
966
- }
967
- if (!request.range) {
968
- return request;
969
- }
970
- else {
971
- var requestedMax = request.range.from + request.range.count;
972
- var missingCount = requestedMax - entry.count;
973
- if (entry.maxCount) {
974
- missingCount = Math.min(missingCount, entry.maxCount);
975
- }
976
- if (missingCount > 0) {
977
- return (0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
978
- }
979
- else {
980
- return null;
981
- }
982
- }
983
- };
984
- ListLoadingTracker.prototype.count = function (request) {
985
- var entry = this.prepare(request).entry;
986
- return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
987
- };
988
- ListLoadingTracker.prototype.append = function (request, response) {
989
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
990
- if (response) {
991
- var list = this.extractList(response);
992
- if (list.count) {
993
- entry.maxCount = list.count;
994
- }
995
- if (!range) {
996
- entry.count = list.items.length;
997
- entry.maxCount = list.items.length;
998
- entry.isComplete = true;
999
- }
1000
- else {
1001
- var from = (list.from == null) ? range.from : list.from;
1002
- if (list.items.length > 0) {
1003
- entry.count = Math.max(entry.count, from + list.items.length);
1004
- }
1005
- if (list.items.length < range.count) {
1006
- entry.maxCount = from + list.items.length;
1007
- entry.count = entry.maxCount;
1008
- entry.isComplete = true;
1009
- }
1010
- }
1011
- }
1012
- else {
1013
- if (range) {
1014
- entry.count = Math.max(entry.count, request.range.from + request.range.count);
1015
- }
1016
- else {
1017
- entry.isComplete = true;
1018
- }
1019
- }
1020
- };
1021
- return ListLoadingTracker;
1022
- }());
1023
- exports.ListLoadingTracker = ListLoadingTracker;
931
+
932
+ Object.defineProperty(exports, "__esModule", { value: true });
933
+ exports.ListLoadingTracker = void 0;
934
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
935
+ var ListLoadingTracker = /** @class */ (function () {
936
+ function ListLoadingTracker(options) {
937
+ this.options = options;
938
+ this.cache = new Map();
939
+ this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
940
+ }
941
+ ListLoadingTracker.prototype.prepare = function (request) {
942
+ var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = (0, tslib_1.__rest)(request, ["filter", "sorting", "search", "range"]);
943
+ var options = {};
944
+ if (filter) {
945
+ options.filter = filter;
946
+ }
947
+ if (sorting) {
948
+ options.sorting = sorting;
949
+ }
950
+ if (search) {
951
+ options.search = search;
952
+ }
953
+ var keyObject = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields);
954
+ var key = JSON.stringify(keyObject);
955
+ var entry = this.cache.get(key);
956
+ if (!entry) {
957
+ entry = { options: options, count: 0, maxCount: null, isComplete: false };
958
+ this.cache.set(key, entry);
959
+ }
960
+ return { options: options, range: range, unknownFields: unknownFields, entry: entry };
961
+ };
962
+ ListLoadingTracker.prototype.diff = function (request) {
963
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
964
+ if (entry.isComplete) {
965
+ return null;
966
+ }
967
+ if (!request.range) {
968
+ return request;
969
+ }
970
+ else {
971
+ var requestedMax = request.range.from + request.range.count;
972
+ var missingCount = requestedMax - entry.count;
973
+ if (entry.maxCount) {
974
+ missingCount = Math.min(missingCount, entry.maxCount);
975
+ }
976
+ if (missingCount > 0) {
977
+ return (0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
978
+ }
979
+ else {
980
+ return null;
981
+ }
982
+ }
983
+ };
984
+ ListLoadingTracker.prototype.count = function (request) {
985
+ var entry = this.prepare(request).entry;
986
+ return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
987
+ };
988
+ ListLoadingTracker.prototype.append = function (request, response) {
989
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
990
+ if (response) {
991
+ var list = this.extractList(response);
992
+ if (list.count) {
993
+ entry.maxCount = list.count;
994
+ }
995
+ if (!range) {
996
+ entry.count = list.items.length;
997
+ entry.maxCount = list.items.length;
998
+ entry.isComplete = true;
999
+ }
1000
+ else {
1001
+ var from = (list.from == null) ? range.from : list.from;
1002
+ if (list.items.length > 0) {
1003
+ entry.count = Math.max(entry.count, from + list.items.length);
1004
+ }
1005
+ if (list.items.length < range.count) {
1006
+ entry.maxCount = from + list.items.length;
1007
+ entry.count = entry.maxCount;
1008
+ entry.isComplete = true;
1009
+ }
1010
+ }
1011
+ }
1012
+ else {
1013
+ if (range) {
1014
+ entry.count = Math.max(entry.count, request.range.from + request.range.count);
1015
+ }
1016
+ else {
1017
+ entry.isComplete = true;
1018
+ }
1019
+ }
1020
+ };
1021
+ return ListLoadingTracker;
1022
+ }());
1023
+ exports.ListLoadingTracker = ListLoadingTracker;
1024
1024
 
1025
1025
 
1026
1026
  /***/ }),
@@ -1033,84 +1033,84 @@ exports.ListLoadingTracker = ListLoadingTracker;
1033
1033
  /***/ (function(module, exports, __webpack_require__) {
1034
1034
 
1035
1035
  "use strict";
1036
-
1037
- Object.defineProperty(exports, "__esModule", { value: true });
1038
- exports.Loader = void 0;
1039
- var Loader = /** @class */ (function () {
1040
- function Loader(dbRef, getTracker, options) {
1041
- var _this = this;
1042
- this.dbRef = dbRef;
1043
- this.getTracker = getTracker;
1044
- this.options = options;
1045
- this.currentRequests = new Set();
1046
- this.load = function (inputRequest) {
1047
- var result = {
1048
- isComplete: _this.loaded.diff(inputRequest) == null,
1049
- isLoading: false,
1050
- request: inputRequest,
1051
- missing: _this.loadedAndLoading.diff(inputRequest),
1052
- promise: null,
1053
- reload: null,
1054
- };
1055
- result.reload = function () {
1056
- result.missing = inputRequest;
1057
- _this.loadImpl(result);
1058
- };
1059
- if (result.isComplete) {
1060
- // Everything requested is already loaded
1061
- result.isComplete = true;
1062
- result.isLoading = false;
1063
- result.promise = Promise.resolve();
1064
- return result;
1065
- }
1066
- else {
1067
- if (result.missing == null) {
1068
- // Everything requested is either loaded already, or being loaded
1069
- result.isComplete = false;
1070
- result.isLoading = true;
1071
- // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1072
- // So we track all running requests, and await all of them in such case.
1073
- result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1074
- return result;
1075
- }
1076
- else {
1077
- // Something requested is not loaded, nor being loaded. Need to perform a new request.
1078
- _this.loadImpl(result);
1079
- return result;
1080
- }
1081
- }
1082
- };
1083
- this.loaded = getTracker();
1084
- this.loadedAndLoading = getTracker();
1085
- }
1086
- Loader.prototype.loadImpl = function (state) {
1087
- var _this = this;
1088
- this.loadedAndLoading.append(state.missing);
1089
- state.isLoading = true;
1090
- var serverRequest = state.missing;
1091
- if (this.options.clientToServerRequest) {
1092
- serverRequest = this.options.clientToServerRequest(serverRequest);
1093
- }
1094
- state.promise = this.options.api(serverRequest).then(function (result) {
1095
- _this.loaded.append(state.missing, result);
1096
- _this.loadedAndLoading.append(state.missing, result);
1097
- state.missing = null;
1098
- state.isLoading = false;
1099
- state.isComplete = true;
1100
- state.promise = Promise.resolve();
1101
- var flatten = _this.options.convertToPatch(result);
1102
- _this.options.postProcess && _this.options.postProcess(flatten);
1103
- _this.dbRef.commitFetch(flatten);
1104
- });
1105
- this.currentRequests.add(state.promise);
1106
- state.promise.finally(function () {
1107
- _this.currentRequests.delete(state.promise);
1108
- });
1109
- return state.promise;
1110
- };
1111
- return Loader;
1112
- }());
1113
- exports.Loader = Loader;
1036
+
1037
+ Object.defineProperty(exports, "__esModule", { value: true });
1038
+ exports.Loader = void 0;
1039
+ var Loader = /** @class */ (function () {
1040
+ function Loader(dbRef, getTracker, options) {
1041
+ var _this = this;
1042
+ this.dbRef = dbRef;
1043
+ this.getTracker = getTracker;
1044
+ this.options = options;
1045
+ this.currentRequests = new Set();
1046
+ this.load = function (inputRequest) {
1047
+ var result = {
1048
+ isComplete: _this.loaded.diff(inputRequest) == null,
1049
+ isLoading: false,
1050
+ request: inputRequest,
1051
+ missing: _this.loadedAndLoading.diff(inputRequest),
1052
+ promise: null,
1053
+ reload: null,
1054
+ };
1055
+ result.reload = function () {
1056
+ result.missing = inputRequest;
1057
+ _this.loadImpl(result);
1058
+ };
1059
+ if (result.isComplete) {
1060
+ // Everything requested is already loaded
1061
+ result.isComplete = true;
1062
+ result.isLoading = false;
1063
+ result.promise = Promise.resolve();
1064
+ return result;
1065
+ }
1066
+ else {
1067
+ if (result.missing == null) {
1068
+ // Everything requested is either loaded already, or being loaded
1069
+ result.isComplete = false;
1070
+ result.isLoading = true;
1071
+ // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1072
+ // So we track all running requests, and await all of them in such case.
1073
+ result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1074
+ return result;
1075
+ }
1076
+ else {
1077
+ // Something requested is not loaded, nor being loaded. Need to perform a new request.
1078
+ _this.loadImpl(result);
1079
+ return result;
1080
+ }
1081
+ }
1082
+ };
1083
+ this.loaded = getTracker();
1084
+ this.loadedAndLoading = getTracker();
1085
+ }
1086
+ Loader.prototype.loadImpl = function (state) {
1087
+ var _this = this;
1088
+ this.loadedAndLoading.append(state.missing);
1089
+ state.isLoading = true;
1090
+ var serverRequest = state.missing;
1091
+ if (this.options.clientToServerRequest) {
1092
+ serverRequest = this.options.clientToServerRequest(serverRequest);
1093
+ }
1094
+ state.promise = this.options.api(serverRequest).then(function (result) {
1095
+ _this.loaded.append(state.missing, result);
1096
+ _this.loadedAndLoading.append(state.missing, result);
1097
+ state.missing = null;
1098
+ state.isLoading = false;
1099
+ state.isComplete = true;
1100
+ state.promise = Promise.resolve();
1101
+ var flatten = _this.options.convertToPatch(result);
1102
+ _this.options.postProcess && _this.options.postProcess(flatten);
1103
+ _this.dbRef.commitFetch(flatten);
1104
+ });
1105
+ this.currentRequests.add(state.promise);
1106
+ state.promise.finally(function () {
1107
+ _this.currentRequests.delete(state.promise);
1108
+ });
1109
+ return state.promise;
1110
+ };
1111
+ return Loader;
1112
+ }());
1113
+ exports.Loader = Loader;
1114
1114
 
1115
1115
 
1116
1116
  /***/ }),
@@ -1123,25 +1123,25 @@ exports.Loader = Loader;
1123
1123
  /***/ (function(module, exports, __webpack_require__) {
1124
1124
 
1125
1125
  "use strict";
1126
-
1127
- Object.defineProperty(exports, "__esModule", { value: true });
1128
- exports.SimpleLoadingTracker = void 0;
1129
- var SimpleLoadingTracker = /** @class */ (function () {
1130
- function SimpleLoadingTracker() {
1131
- this.set = new Set();
1132
- }
1133
- SimpleLoadingTracker.prototype.getKey = function (request) {
1134
- return JSON.stringify(request);
1135
- };
1136
- SimpleLoadingTracker.prototype.diff = function (request) {
1137
- return this.set.has(this.getKey(request)) ? null : request;
1138
- };
1139
- SimpleLoadingTracker.prototype.append = function (request, result) {
1140
- this.set.add(this.getKey(request));
1141
- };
1142
- return SimpleLoadingTracker;
1143
- }());
1144
- exports.SimpleLoadingTracker = SimpleLoadingTracker;
1126
+
1127
+ Object.defineProperty(exports, "__esModule", { value: true });
1128
+ exports.SimpleLoadingTracker = void 0;
1129
+ var SimpleLoadingTracker = /** @class */ (function () {
1130
+ function SimpleLoadingTracker() {
1131
+ this.set = new Set();
1132
+ }
1133
+ SimpleLoadingTracker.prototype.getKey = function (request) {
1134
+ return JSON.stringify(request);
1135
+ };
1136
+ SimpleLoadingTracker.prototype.diff = function (request) {
1137
+ return this.set.has(this.getKey(request)) ? null : request;
1138
+ };
1139
+ SimpleLoadingTracker.prototype.append = function (request, result) {
1140
+ this.set.add(this.getKey(request));
1141
+ };
1142
+ return SimpleLoadingTracker;
1143
+ }());
1144
+ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1145
1145
 
1146
1146
 
1147
1147
  /***/ }),
@@ -1154,17 +1154,17 @@ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1154
1154
  /***/ (function(module, exports, __webpack_require__) {
1155
1155
 
1156
1156
  "use strict";
1157
-
1158
- Object.defineProperty(exports, "__esModule", { value: true });
1159
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1160
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1161
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1162
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1163
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1164
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1165
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1166
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1167
- (0, tslib_1.__exportStar)(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1157
+
1158
+ Object.defineProperty(exports, "__esModule", { value: true });
1159
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1160
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1161
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1162
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1163
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1164
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1165
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1166
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1167
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1168
1168
 
1169
1169
 
1170
1170
  /***/ }),
@@ -1177,200 +1177,200 @@ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.
1177
1177
  /***/ (function(module, exports, __webpack_require__) {
1178
1178
 
1179
1179
  "use strict";
1180
-
1181
- Object.defineProperty(exports, "__esModule", { value: true });
1182
- exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1183
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1184
- var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1185
- var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
1186
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1187
- var lodash_groupby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1188
- var lodash_map_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.map */ "lodash.map"));
1189
- var lodash_merge_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1190
- var lodash_countby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1191
- var lodash_filter_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1192
- var lodash_foreach_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1193
- var lodash_pick_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1194
- function unionPatches(patches) {
1195
- var result = {};
1196
- patches.forEach(function (patch) {
1197
- (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1198
- result[tableName] = result[tableName] ? (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], result[tableName], true), patch[tableName], true) : patch[tableName];
1199
- });
1200
- });
1201
- return result;
1202
- }
1203
- exports.unionPatches = unionPatches;
1204
- function mergeEntityPatches(tables, patch) {
1205
- var result = {};
1206
- (0, utils_1.objectKeys)(patch).forEach(function (key) {
1207
- var table = tables[key];
1208
- var groupedEntities = (0, lodash_groupby_1.default)(patch[key], function (item) { return table.getId(item); });
1209
- var tablePatch = (0, lodash_map_1.default)(groupedEntities, function (entities) {
1210
- var result = lodash_merge_1.default.apply(void 0, (0, tslib_1.__spreadArray)([{}], entities, false));
1211
- if (true) {
1212
- var props = (0, utils_1.objectKeys)(result).filter(function (prop) {
1213
- return Object.keys((0, lodash_countby_1.default)(entities.filter(function (entity) {
1214
- return entity[prop] !== undefined;
1215
- }), function (entity) { return entity[prop]; })).length > 1;
1216
- });
1217
- if (props.length) {
1218
- console.warn.apply(console, (0, tslib_1.__spreadArray)(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities, false));
1219
- }
1220
- }
1221
- return result;
1222
- });
1223
- result[key] = tablePatch;
1224
- });
1225
- return result;
1226
- }
1227
- exports.mergeEntityPatches = mergeEntityPatches;
1228
- function flattenResponseHelper(result, object, tablesByTypeName) {
1229
- if (Array.isArray(object)) {
1230
- object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1231
- }
1232
- else if (typeof object === 'object') {
1233
- var clone = {};
1234
- var tableKey = void 0;
1235
- var fields = {};
1236
- if ('__typename' in object) {
1237
- var table = tablesByTypeName[object.__typename];
1238
- if (table) {
1239
- tableKey = table.schema.tableName;
1240
- fields = table.schema.fields;
1241
- }
1242
- }
1243
- for (var key in object) {
1244
- var value = object[key];
1245
- var field = fields[key];
1246
- if ((field && !!field.disableFlatten)
1247
- || typeof value !== 'object'
1248
- || value === null
1249
- || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1250
- clone[key] = value;
1251
- }
1252
- else {
1253
- flattenResponseHelper(result, value, tablesByTypeName);
1254
- }
1255
- }
1256
- if (tableKey) {
1257
- result[tableKey].push(clone);
1258
- }
1259
- }
1260
- }
1261
- function flattenResponse(response, tables) {
1262
- var result = {};
1263
- var tablesByTypeName = {};
1264
- Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1265
- (0, utils_1.objectKeys)(tables).forEach(function (tableName) { return tablesByTypeName; });
1266
- (0, utils_1.objectKeys)(tables).forEach(function (key) { return result[key] = []; });
1267
- flattenResponseHelper(result, response, tablesByTypeName);
1268
- return result;
1269
- }
1270
- exports.flattenResponse = flattenResponse;
1271
- function isPatchBlank(patch) {
1272
- return !(0, utils_1.objectKeys)(patch).some(function (key) { return patch[key].length > 0; });
1273
- }
1274
- exports.isPatchBlank = isPatchBlank;
1275
- /**
1276
- * Given several patches, creates a new single patch with all fields from all entities in all patches.
1277
- */
1278
- function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1279
- var result = {};
1280
- (0, utils_1.objectKeys)(updatedDb.tables).forEach(function (entityName) {
1281
- var table = updatedDb.tables[entityName];
1282
- var schema = table.schema;
1283
- var ids = I.Set();
1284
- patches.forEach(function (patch) {
1285
- var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1286
- ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1287
- });
1288
- var entities = ids
1289
- .map(function (id) { return table.byId(id); })
1290
- .filter(function (e) { return !isClientOnly(e, schema); })
1291
- .toArray();
1292
- if (entities.length > 0) {
1293
- result[entityName] = entities;
1294
- }
1295
- });
1296
- return result;
1297
- }
1298
- exports.makeCumulativePatch = makeCumulativePatch;
1299
- function isClientOnly(entity, schema) {
1300
- if (typeof schema.isClientOnly === 'function') {
1301
- return schema.isClientOnly(entity);
1302
- }
1303
- return !!schema.isClientOnly;
1304
- }
1305
- exports.isClientOnly = isClientOnly;
1306
- function getId(entity, schema) {
1307
- if (typeof schema.primaryKey == 'string') {
1308
- return entity[schema.primaryKey];
1309
- }
1310
- var result = [];
1311
- (0, lodash_foreach_1.default)((0, lodash_pick_1.default)(entity, schema.primaryKey), function (value) {
1312
- result.push(value);
1313
- });
1314
- return result;
1315
- }
1316
- exports.getId = getId;
1317
- function isNew(entity, schema, clientIdsMap) {
1318
- var id = getId(entity, schema);
1319
- return !clientIdsMap.clientToServer(id);
1320
- }
1321
- exports.isNew = isNew;
1322
- function hasServerFields(entity, schema, clientIdsMap, tables) {
1323
- var fullEntity = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1324
- if (isClientOnly(fullEntity, schema)) {
1325
- return false;
1326
- }
1327
- return (0, utils_1.objectKeys)(entity).some(function (fieldName) {
1328
- var fieldSchema = schema.fields[fieldName];
1329
- return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1330
- });
1331
- }
1332
- exports.hasServerFields = hasServerFields;
1333
- function getParentEntities(patch, tables) {
1334
- var dependenciesPatch = {};
1335
- (0, utils_1.objectKeys)(patch).forEach(function (key) {
1336
- var table = tables[key];
1337
- var tableSchema = table.schema;
1338
- var fields = (0, lodash_filter_1.default)((0, lodash_map_1.default)(tableSchema.fields, function (field, name) { return ((0, tslib_1.__assign)((0, tslib_1.__assign)({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1339
- var tablePatch = patch[key];
1340
- fields.forEach(function (field) {
1341
- var tableName = field.fk.tableName, name = field.name;
1342
- tablePatch.forEach(function (entity) {
1343
- var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1344
- var dbEntity = table.byId(table.getId(entity));
1345
- var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1346
- var idFields = (0, lodash_pick_1.default)(parentEntity, tables[actualTableName].schema.primaryKey);
1347
- if (parentEntity) {
1348
- dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1349
- dependenciesPatch[actualTableName].push(idFields);
1350
- }
1351
- });
1352
- });
1353
- });
1354
- return dependenciesPatch;
1355
- }
1356
- exports.getParentEntities = getParentEntities;
1357
- function getEntityParentDependencies(entity, entityName, tables) {
1358
- var _a;
1359
- var patch = (_a = {}, _a[entityName] = [entity], _a);
1360
- var resultPatches = [];
1361
- while (true) {
1362
- var parents = getParentEntities(patch, tables);
1363
- if (isPatchBlank(parents)) {
1364
- break;
1365
- }
1366
- resultPatches.push(parents);
1367
- patch = parents;
1368
- }
1369
- var result = unionPatches((0, tslib_1.__spreadArray)([patch], resultPatches, true));
1370
- result = mergeEntityPatches(tables, result);
1371
- return result;
1372
- }
1373
- exports.getEntityParentDependencies = getEntityParentDependencies;
1180
+
1181
+ Object.defineProperty(exports, "__esModule", { value: true });
1182
+ exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1183
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1184
+ var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1185
+ var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
1186
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1187
+ var lodash_groupby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1188
+ var lodash_map_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.map */ "lodash.map"));
1189
+ var lodash_merge_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1190
+ var lodash_countby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1191
+ var lodash_filter_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1192
+ var lodash_foreach_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1193
+ var lodash_pick_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1194
+ function unionPatches(patches) {
1195
+ var result = {};
1196
+ patches.forEach(function (patch) {
1197
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1198
+ result[tableName] = result[tableName] ? (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], result[tableName], true), patch[tableName], true) : patch[tableName];
1199
+ });
1200
+ });
1201
+ return result;
1202
+ }
1203
+ exports.unionPatches = unionPatches;
1204
+ function mergeEntityPatches(tables, patch) {
1205
+ var result = {};
1206
+ (0, utils_1.objectKeys)(patch).forEach(function (key) {
1207
+ var table = tables[key];
1208
+ var groupedEntities = (0, lodash_groupby_1.default)(patch[key], function (item) { return table.getId(item); });
1209
+ var tablePatch = (0, lodash_map_1.default)(groupedEntities, function (entities) {
1210
+ var result = lodash_merge_1.default.apply(void 0, (0, tslib_1.__spreadArray)([{}], entities, false));
1211
+ if (true) {
1212
+ var props = (0, utils_1.objectKeys)(result).filter(function (prop) {
1213
+ return Object.keys((0, lodash_countby_1.default)(entities.filter(function (entity) {
1214
+ return entity[prop] !== undefined;
1215
+ }), function (entity) { return entity[prop]; })).length > 1;
1216
+ });
1217
+ if (props.length) {
1218
+ console.warn.apply(console, (0, tslib_1.__spreadArray)(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities, false));
1219
+ }
1220
+ }
1221
+ return result;
1222
+ });
1223
+ result[key] = tablePatch;
1224
+ });
1225
+ return result;
1226
+ }
1227
+ exports.mergeEntityPatches = mergeEntityPatches;
1228
+ function flattenResponseHelper(result, object, tablesByTypeName) {
1229
+ if (Array.isArray(object)) {
1230
+ object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1231
+ }
1232
+ else if (typeof object === 'object') {
1233
+ var clone = {};
1234
+ var tableKey = void 0;
1235
+ var fields = {};
1236
+ if ('__typename' in object) {
1237
+ var table = tablesByTypeName[object.__typename];
1238
+ if (table) {
1239
+ tableKey = table.schema.tableName;
1240
+ fields = table.schema.fields;
1241
+ }
1242
+ }
1243
+ for (var key in object) {
1244
+ var value = object[key];
1245
+ var field = fields[key];
1246
+ if ((field && !!field.disableFlatten)
1247
+ || typeof value !== 'object'
1248
+ || value === null
1249
+ || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1250
+ clone[key] = value;
1251
+ }
1252
+ else {
1253
+ flattenResponseHelper(result, value, tablesByTypeName);
1254
+ }
1255
+ }
1256
+ if (tableKey) {
1257
+ result[tableKey].push(clone);
1258
+ }
1259
+ }
1260
+ }
1261
+ function flattenResponse(response, tables) {
1262
+ var result = {};
1263
+ var tablesByTypeName = {};
1264
+ Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1265
+ (0, utils_1.objectKeys)(tables).forEach(function (tableName) { return tablesByTypeName; });
1266
+ (0, utils_1.objectKeys)(tables).forEach(function (key) { return result[key] = []; });
1267
+ flattenResponseHelper(result, response, tablesByTypeName);
1268
+ return result;
1269
+ }
1270
+ exports.flattenResponse = flattenResponse;
1271
+ function isPatchBlank(patch) {
1272
+ return !(0, utils_1.objectKeys)(patch).some(function (key) { return patch[key].length > 0; });
1273
+ }
1274
+ exports.isPatchBlank = isPatchBlank;
1275
+ /**
1276
+ * Given several patches, creates a new single patch with all fields from all entities in all patches.
1277
+ */
1278
+ function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1279
+ var result = {};
1280
+ (0, utils_1.objectKeys)(updatedDb.tables).forEach(function (entityName) {
1281
+ var table = updatedDb.tables[entityName];
1282
+ var schema = table.schema;
1283
+ var ids = I.Set();
1284
+ patches.forEach(function (patch) {
1285
+ var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1286
+ ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1287
+ });
1288
+ var entities = ids
1289
+ .map(function (id) { return table.byId(id); })
1290
+ .filter(function (e) { return !isClientOnly(e, schema); })
1291
+ .toArray();
1292
+ if (entities.length > 0) {
1293
+ result[entityName] = entities;
1294
+ }
1295
+ });
1296
+ return result;
1297
+ }
1298
+ exports.makeCumulativePatch = makeCumulativePatch;
1299
+ function isClientOnly(entity, schema) {
1300
+ if (typeof schema.isClientOnly === 'function') {
1301
+ return schema.isClientOnly(entity);
1302
+ }
1303
+ return !!schema.isClientOnly;
1304
+ }
1305
+ exports.isClientOnly = isClientOnly;
1306
+ function getId(entity, schema) {
1307
+ if (typeof schema.primaryKey == 'string') {
1308
+ return entity[schema.primaryKey];
1309
+ }
1310
+ var result = [];
1311
+ (0, lodash_foreach_1.default)((0, lodash_pick_1.default)(entity, schema.primaryKey), function (value) {
1312
+ result.push(value);
1313
+ });
1314
+ return result;
1315
+ }
1316
+ exports.getId = getId;
1317
+ function isNew(entity, schema, clientIdsMap) {
1318
+ var id = getId(entity, schema);
1319
+ return !clientIdsMap.clientToServer(id);
1320
+ }
1321
+ exports.isNew = isNew;
1322
+ function hasServerFields(entity, schema, clientIdsMap, tables) {
1323
+ var fullEntity = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1324
+ if (isClientOnly(fullEntity, schema)) {
1325
+ return false;
1326
+ }
1327
+ return (0, utils_1.objectKeys)(entity).some(function (fieldName) {
1328
+ var fieldSchema = schema.fields[fieldName];
1329
+ return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1330
+ });
1331
+ }
1332
+ exports.hasServerFields = hasServerFields;
1333
+ function getParentEntities(patch, tables) {
1334
+ var dependenciesPatch = {};
1335
+ (0, utils_1.objectKeys)(patch).forEach(function (key) {
1336
+ var table = tables[key];
1337
+ var tableSchema = table.schema;
1338
+ var fields = (0, lodash_filter_1.default)((0, lodash_map_1.default)(tableSchema.fields, function (field, name) { return ((0, tslib_1.__assign)((0, tslib_1.__assign)({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1339
+ var tablePatch = patch[key];
1340
+ fields.forEach(function (field) {
1341
+ var tableName = field.fk.tableName, name = field.name;
1342
+ tablePatch.forEach(function (entity) {
1343
+ var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1344
+ var dbEntity = table.byId(table.getId(entity));
1345
+ var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1346
+ var idFields = (0, lodash_pick_1.default)(parentEntity, tables[actualTableName].schema.primaryKey);
1347
+ if (parentEntity) {
1348
+ dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1349
+ dependenciesPatch[actualTableName].push(idFields);
1350
+ }
1351
+ });
1352
+ });
1353
+ });
1354
+ return dependenciesPatch;
1355
+ }
1356
+ exports.getParentEntities = getParentEntities;
1357
+ function getEntityParentDependencies(entity, entityName, tables) {
1358
+ var _a;
1359
+ var patch = (_a = {}, _a[entityName] = [entity], _a);
1360
+ var resultPatches = [];
1361
+ while (true) {
1362
+ var parents = getParentEntities(patch, tables);
1363
+ if (isPatchBlank(parents)) {
1364
+ break;
1365
+ }
1366
+ resultPatches.push(parents);
1367
+ patch = parents;
1368
+ }
1369
+ var result = unionPatches((0, tslib_1.__spreadArray)([patch], resultPatches, true));
1370
+ result = mergeEntityPatches(tables, result);
1371
+ return result;
1372
+ }
1373
+ exports.getEntityParentDependencies = getEntityParentDependencies;
1374
1374
 
1375
1375
 
1376
1376
  /***/ }),
@@ -1383,27 +1383,27 @@ exports.getEntityParentDependencies = getEntityParentDependencies;
1383
1383
  /***/ (function(module, exports, __webpack_require__) {
1384
1384
 
1385
1385
  "use strict";
1386
-
1387
- Object.defineProperty(exports, "__esModule", { value: true });
1388
- exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1389
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1390
- var react_1 = __webpack_require__(/*! react */ "react");
1391
- exports.DbContext = (0, react_1.createContext)(null);
1392
- function useDbRef() {
1393
- return (0, react_1.useContext)(exports.DbContext);
1394
- }
1395
- exports.useDbRef = useDbRef;
1396
- function useDbView(fn, params, options) {
1397
- var dbRef = useDbRef();
1398
- var _a = (0, react_1.useState)(), state = _a[0], setState = _a[1];
1399
- var subscription = (0, react_1.useMemo)(function () { return dbRef.subscribe((0, tslib_1.__assign)({ compute: fn }, options), params, setState); }, []);
1400
- subscription.update(params);
1401
- (0, react_1.useEffect)(function () {
1402
- return function () { return subscription.unsubscribe(); };
1403
- }, []);
1404
- return subscription.currentValue;
1405
- }
1406
- exports.useDbView = useDbView;
1386
+
1387
+ Object.defineProperty(exports, "__esModule", { value: true });
1388
+ exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1389
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1390
+ var react_1 = __webpack_require__(/*! react */ "react");
1391
+ exports.DbContext = (0, react_1.createContext)(null);
1392
+ function useDbRef() {
1393
+ return (0, react_1.useContext)(exports.DbContext);
1394
+ }
1395
+ exports.useDbRef = useDbRef;
1396
+ function useDbView(fn, params, options) {
1397
+ var dbRef = useDbRef();
1398
+ var _a = (0, react_1.useState)(), state = _a[0], setState = _a[1];
1399
+ var subscription = (0, react_1.useMemo)(function () { return dbRef.subscribe((0, tslib_1.__assign)({ compute: fn }, options), params, setState); }, []);
1400
+ subscription.update(params);
1401
+ (0, react_1.useEffect)(function () {
1402
+ return function () { return subscription.unsubscribe(); };
1403
+ }, []);
1404
+ return subscription.currentValue;
1405
+ }
1406
+ exports.useDbView = useDbView;
1407
1407
 
1408
1408
 
1409
1409
  /***/ }),
@@ -1416,190 +1416,190 @@ exports.useDbView = useDbView;
1416
1416
  /***/ (function(module, exports, __webpack_require__) {
1417
1417
 
1418
1418
  "use strict";
1419
-
1420
- Object.defineProperty(exports, "__esModule", { value: true });
1421
- exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1422
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1423
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1424
- var lastTempId = -1;
1425
- function getTempId() {
1426
- return --lastTempId;
1427
- }
1428
- exports.getTempId = getTempId;
1429
- function isTempId(val) {
1430
- return typeof val === 'number' && val < 0;
1431
- }
1432
- exports.isTempId = isTempId;
1433
- var TempIdMap = /** @class */ (function () {
1434
- function TempIdMap(db) {
1435
- var _this = this;
1436
- this.db = db;
1437
- this.serverToClientIds = new Map();
1438
- this.clientToServerIds = new Map();
1439
- this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1440
- this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1441
- this.clientToServerRequest = function (request) {
1442
- request = (0, tslib_1.__assign)({}, request);
1443
- if (request.filter) {
1444
- request.filter = _this.clientToServerDataFilter(request.filter);
1445
- }
1446
- return request;
1447
- };
1448
- this.clientToServerDataFilter = function (filter) {
1449
- filter = (0, tslib_1.__assign)({}, filter);
1450
- var keys = Object.keys(filter);
1451
- // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1452
- // We need to invent better heuristics or a schema otherwise.
1453
- var clientToServer = function (id) {
1454
- var found = _this.clientToServer(id);
1455
- if (found) {
1456
- return found;
1457
- }
1458
- else {
1459
- return id;
1460
- }
1461
- };
1462
- for (var n = 0; n < keys.length; n++) {
1463
- var key = keys[n];
1464
- var condition = filter[key];
1465
- if (condition != null && typeof condition === "object") {
1466
- condition = (0, tslib_1.__assign)({}, condition);
1467
- if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1468
- condition.in = condition.in.map(clientToServer);
1469
- }
1470
- }
1471
- else {
1472
- condition = clientToServer(condition);
1473
- }
1474
- filter[key] = condition;
1475
- }
1476
- return filter;
1477
- };
1478
- }
1479
- TempIdMap.prototype.copyPatch = function (patch) {
1480
- var newPatch = (0, tslib_1.__assign)({}, patch);
1481
- (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1482
- var tablePatch = patch[tableName].map(function (entityPatch) { return ((0, tslib_1.__assign)({}, entityPatch)); });
1483
- newPatch[tableName] = tablePatch;
1484
- });
1485
- return newPatch;
1486
- };
1487
- // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1488
- TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1489
- var _this = this;
1490
- (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1491
- var schema = _this.db.tables[tableName].schema;
1492
- var fields = (0, utils_1.objectKeys)(schema.fields || [])
1493
- .map(function (fieldName) {
1494
- var fieldSchema = schema.fields[fieldName];
1495
- if (filter(fieldSchema, fieldName)) {
1496
- return { name: fieldName, schema: fieldSchema };
1497
- }
1498
- })
1499
- .filter(function (f) { return !!f; });
1500
- if (!fields.length) {
1501
- return;
1502
- }
1503
- patch[tableName].forEach(function (entityPatch) {
1504
- for (var n = 0; n < fields.length; n++) {
1505
- var field = fields[n];
1506
- var fieldValue = entityPatch[field.name];
1507
- callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1508
- }
1509
- });
1510
- });
1511
- };
1512
- TempIdMap.prototype.getServerToClientMap = function (tableName) {
1513
- var existing = this.serverToClientIds.get(tableName);
1514
- if (existing) {
1515
- return existing;
1516
- }
1517
- else {
1518
- var newMap = new Map();
1519
- this.serverToClientIds.set(tableName, newMap);
1520
- return newMap;
1521
- }
1522
- };
1523
- TempIdMap.prototype.serverToClientPatch = function (patch) {
1524
- var _this = this;
1525
- patch = this.copyPatch(patch);
1526
- // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1527
- this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1528
- var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1529
- if (!clientId) {
1530
- clientId = getTempId();
1531
- _this.clientToServerIds.set(clientId, fieldValue);
1532
- _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1533
- }
1534
- entityPatch[fieldName] = clientId;
1535
- });
1536
- this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1537
- var isUndefined = typeof (fieldValue) === 'undefined';
1538
- if (fieldSchema.default != null && fieldValue == null) {
1539
- fieldValue = fieldSchema.default;
1540
- isUndefined = false;
1541
- }
1542
- if (fieldSchema.fk && fieldValue != null) {
1543
- var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1544
- var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1545
- if (!clientId) {
1546
- clientId = getTempId();
1547
- _this.clientToServerIds.set(clientId, fieldValue);
1548
- _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1549
- }
1550
- fieldValue = clientId;
1551
- }
1552
- if (!isUndefined && fieldSchema.toClient) {
1553
- fieldValue = fieldSchema.toClient(fieldValue);
1554
- }
1555
- if (!isUndefined) {
1556
- entityPatch[fieldName] = fieldValue;
1557
- }
1558
- });
1559
- return patch;
1560
- };
1561
- TempIdMap.prototype.clientToServerPatch = function (patch) {
1562
- var _this = this;
1563
- patch = this.copyPatch(patch);
1564
- this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1565
- if (fieldValue != null) {
1566
- var existingId = _this.clientToServerIds.get(fieldValue);
1567
- if (existingId) {
1568
- entityPatch[fieldName] = existingId;
1569
- }
1570
- }
1571
- });
1572
- this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1573
- entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1574
- });
1575
- this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1576
- delete entityPatch[fieldName];
1577
- });
1578
- return patch;
1579
- };
1580
- TempIdMap.prototype.appendServerMapping = function (response) {
1581
- var _this = this;
1582
- (0, utils_1.objectKeys)(response.submit).forEach(function (tableName) {
1583
- if (_this.db.tables[tableName]) {
1584
- var tablePatch = response.submit[tableName];
1585
- if (tablePatch) {
1586
- var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1587
- var table_1 = _this.db.tables[tableName];
1588
- tablePatch.forEach(function (patch) {
1589
- if (isTempId(patch.id)) {
1590
- var clientId = patch.id;
1591
- var serverId = table_1.getId(patch.payload);
1592
- serverToClientIds_1.set(serverId, clientId);
1593
- _this.clientToServerIds.set(clientId, serverId);
1594
- }
1595
- });
1596
- }
1597
- }
1598
- });
1599
- };
1600
- return TempIdMap;
1601
- }());
1602
- exports.TempIdMap = TempIdMap;
1419
+
1420
+ Object.defineProperty(exports, "__esModule", { value: true });
1421
+ exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1422
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1423
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1424
+ var lastTempId = -1;
1425
+ function getTempId() {
1426
+ return --lastTempId;
1427
+ }
1428
+ exports.getTempId = getTempId;
1429
+ function isTempId(val) {
1430
+ return typeof val === 'number' && val < 0;
1431
+ }
1432
+ exports.isTempId = isTempId;
1433
+ var TempIdMap = /** @class */ (function () {
1434
+ function TempIdMap(db) {
1435
+ var _this = this;
1436
+ this.db = db;
1437
+ this.serverToClientIds = new Map();
1438
+ this.clientToServerIds = new Map();
1439
+ this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1440
+ this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1441
+ this.clientToServerRequest = function (request) {
1442
+ request = (0, tslib_1.__assign)({}, request);
1443
+ if (request.filter) {
1444
+ request.filter = _this.clientToServerDataFilter(request.filter);
1445
+ }
1446
+ return request;
1447
+ };
1448
+ this.clientToServerDataFilter = function (filter) {
1449
+ filter = (0, tslib_1.__assign)({}, filter);
1450
+ var keys = Object.keys(filter);
1451
+ // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1452
+ // We need to invent better heuristics or a schema otherwise.
1453
+ var clientToServer = function (id) {
1454
+ var found = _this.clientToServer(id);
1455
+ if (found) {
1456
+ return found;
1457
+ }
1458
+ else {
1459
+ return id;
1460
+ }
1461
+ };
1462
+ for (var n = 0; n < keys.length; n++) {
1463
+ var key = keys[n];
1464
+ var condition = filter[key];
1465
+ if (condition != null && typeof condition === "object") {
1466
+ condition = (0, tslib_1.__assign)({}, condition);
1467
+ if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1468
+ condition.in = condition.in.map(clientToServer);
1469
+ }
1470
+ }
1471
+ else {
1472
+ condition = clientToServer(condition);
1473
+ }
1474
+ filter[key] = condition;
1475
+ }
1476
+ return filter;
1477
+ };
1478
+ }
1479
+ TempIdMap.prototype.copyPatch = function (patch) {
1480
+ var newPatch = (0, tslib_1.__assign)({}, patch);
1481
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1482
+ var tablePatch = patch[tableName].map(function (entityPatch) { return ((0, tslib_1.__assign)({}, entityPatch)); });
1483
+ newPatch[tableName] = tablePatch;
1484
+ });
1485
+ return newPatch;
1486
+ };
1487
+ // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1488
+ TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1489
+ var _this = this;
1490
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1491
+ var schema = _this.db.tables[tableName].schema;
1492
+ var fields = (0, utils_1.objectKeys)(schema.fields || [])
1493
+ .map(function (fieldName) {
1494
+ var fieldSchema = schema.fields[fieldName];
1495
+ if (filter(fieldSchema, fieldName)) {
1496
+ return { name: fieldName, schema: fieldSchema };
1497
+ }
1498
+ })
1499
+ .filter(function (f) { return !!f; });
1500
+ if (!fields.length) {
1501
+ return;
1502
+ }
1503
+ patch[tableName].forEach(function (entityPatch) {
1504
+ for (var n = 0; n < fields.length; n++) {
1505
+ var field = fields[n];
1506
+ var fieldValue = entityPatch[field.name];
1507
+ callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1508
+ }
1509
+ });
1510
+ });
1511
+ };
1512
+ TempIdMap.prototype.getServerToClientMap = function (tableName) {
1513
+ var existing = this.serverToClientIds.get(tableName);
1514
+ if (existing) {
1515
+ return existing;
1516
+ }
1517
+ else {
1518
+ var newMap = new Map();
1519
+ this.serverToClientIds.set(tableName, newMap);
1520
+ return newMap;
1521
+ }
1522
+ };
1523
+ TempIdMap.prototype.serverToClientPatch = function (patch) {
1524
+ var _this = this;
1525
+ patch = this.copyPatch(patch);
1526
+ // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1527
+ this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1528
+ var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1529
+ if (!clientId) {
1530
+ clientId = getTempId();
1531
+ _this.clientToServerIds.set(clientId, fieldValue);
1532
+ _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1533
+ }
1534
+ entityPatch[fieldName] = clientId;
1535
+ });
1536
+ this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1537
+ var isUndefined = typeof (fieldValue) === 'undefined';
1538
+ if (fieldSchema.default != null && fieldValue == null) {
1539
+ fieldValue = fieldSchema.default;
1540
+ isUndefined = false;
1541
+ }
1542
+ if (fieldSchema.fk && fieldValue != null) {
1543
+ var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1544
+ var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1545
+ if (!clientId) {
1546
+ clientId = getTempId();
1547
+ _this.clientToServerIds.set(clientId, fieldValue);
1548
+ _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1549
+ }
1550
+ fieldValue = clientId;
1551
+ }
1552
+ if (!isUndefined && fieldSchema.toClient) {
1553
+ fieldValue = fieldSchema.toClient(fieldValue);
1554
+ }
1555
+ if (!isUndefined) {
1556
+ entityPatch[fieldName] = fieldValue;
1557
+ }
1558
+ });
1559
+ return patch;
1560
+ };
1561
+ TempIdMap.prototype.clientToServerPatch = function (patch) {
1562
+ var _this = this;
1563
+ patch = this.copyPatch(patch);
1564
+ this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1565
+ if (fieldValue != null) {
1566
+ var existingId = _this.clientToServerIds.get(fieldValue);
1567
+ if (existingId) {
1568
+ entityPatch[fieldName] = existingId;
1569
+ }
1570
+ }
1571
+ });
1572
+ this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1573
+ entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1574
+ });
1575
+ this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1576
+ delete entityPatch[fieldName];
1577
+ });
1578
+ return patch;
1579
+ };
1580
+ TempIdMap.prototype.appendServerMapping = function (response) {
1581
+ var _this = this;
1582
+ (0, utils_1.objectKeys)(response.submit).forEach(function (tableName) {
1583
+ if (_this.db.tables[tableName]) {
1584
+ var tablePatch = response.submit[tableName];
1585
+ if (tablePatch) {
1586
+ var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1587
+ var table_1 = _this.db.tables[tableName];
1588
+ tablePatch.forEach(function (patch) {
1589
+ if (isTempId(patch.id)) {
1590
+ var clientId = patch.id;
1591
+ var serverId = table_1.getId(patch.payload);
1592
+ serverToClientIds_1.set(serverId, clientId);
1593
+ _this.clientToServerIds.set(clientId, serverId);
1594
+ }
1595
+ });
1596
+ }
1597
+ }
1598
+ });
1599
+ };
1600
+ return TempIdMap;
1601
+ }());
1602
+ exports.TempIdMap = TempIdMap;
1603
1603
 
1604
1604
 
1605
1605
  /***/ }),
@@ -1612,14 +1612,14 @@ exports.TempIdMap = TempIdMap;
1612
1612
  /***/ (function(module, exports, __webpack_require__) {
1613
1613
 
1614
1614
  "use strict";
1615
-
1616
- Object.defineProperty(exports, "__esModule", { value: true });
1617
- exports.DbRelationType = void 0;
1618
- var DbRelationType;
1619
- (function (DbRelationType) {
1620
- DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1621
- DbRelationType[DbRelationType["Association"] = 1] = "Association";
1622
- })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1615
+
1616
+ Object.defineProperty(exports, "__esModule", { value: true });
1617
+ exports.DbRelationType = void 0;
1618
+ var DbRelationType;
1619
+ (function (DbRelationType) {
1620
+ DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1621
+ DbRelationType[DbRelationType["Association"] = 1] = "Association";
1622
+ })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1623
1623
 
1624
1624
 
1625
1625
  /***/ }),
@@ -1632,46 +1632,46 @@ var DbRelationType;
1632
1632
  /***/ (function(module, exports, __webpack_require__) {
1633
1633
 
1634
1634
  "use strict";
1635
-
1636
- Object.defineProperty(exports, "__esModule", { value: true });
1637
- exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1638
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1639
- var shallowequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! shallowequal */ "shallowequal"));
1640
- var lodash_zip_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1641
- var lodash_transform_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1642
- var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1643
- // TBD: New typescript would contain better typing for this. Remove this hack after update.
1644
- exports.objectKeys = Object.keys;
1645
- function defaultCompareViewDependencies(prev, next) {
1646
- if (Array.isArray(prev) && Array.isArray(next)) {
1647
- if (prev.length === next.length) {
1648
- return (0, lodash_zip_1.default)(prev, next).every(function (_a) {
1649
- var p = _a[0], n = _a[1];
1650
- return (0, shallowequal_1.default)(p, n);
1651
- });
1652
- }
1653
- return false;
1654
- }
1655
- return (0, shallowequal_1.default)(prev, next);
1656
- }
1657
- exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1658
- /**
1659
- * Deep diff between two object, using lodash
1660
- * @param {Object} object Object compared
1661
- * @param {Object} base Object to compare with
1662
- * @return {Object} Return a new object who represent the diff
1663
- */
1664
- function difference(object, base) {
1665
- function changes(object, base) {
1666
- return (0, lodash_transform_1.default)(object, function (result, value, key) {
1667
- if (!(0, lodash_isequal_1.default)(value, base[key])) {
1668
- result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1669
- }
1670
- });
1671
- }
1672
- return changes(object, base);
1673
- }
1674
- exports.difference = difference;
1635
+
1636
+ Object.defineProperty(exports, "__esModule", { value: true });
1637
+ exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1638
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1639
+ var shallowequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! shallowequal */ "shallowequal"));
1640
+ var lodash_zip_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1641
+ var lodash_transform_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1642
+ var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1643
+ // TBD: New typescript would contain better typing for this. Remove this hack after update.
1644
+ exports.objectKeys = Object.keys;
1645
+ function defaultCompareViewDependencies(prev, next) {
1646
+ if (Array.isArray(prev) && Array.isArray(next)) {
1647
+ if (prev.length === next.length) {
1648
+ return (0, lodash_zip_1.default)(prev, next).every(function (_a) {
1649
+ var p = _a[0], n = _a[1];
1650
+ return (0, shallowequal_1.default)(p, n);
1651
+ });
1652
+ }
1653
+ return false;
1654
+ }
1655
+ return (0, shallowequal_1.default)(prev, next);
1656
+ }
1657
+ exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1658
+ /**
1659
+ * Deep diff between two object, using lodash
1660
+ * @param {Object} object Object compared
1661
+ * @param {Object} base Object to compare with
1662
+ * @return {Object} Return a new object who represent the diff
1663
+ */
1664
+ function difference(object, base) {
1665
+ function changes(object, base) {
1666
+ return (0, lodash_transform_1.default)(object, function (result, value, key) {
1667
+ if (!(0, lodash_isequal_1.default)(value, base[key])) {
1668
+ result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1669
+ }
1670
+ });
1671
+ }
1672
+ return changes(object, base);
1673
+ }
1674
+ exports.difference = difference;
1675
1675
 
1676
1676
 
1677
1677
  /***/ }),
@@ -1683,7 +1683,7 @@ exports.difference = difference;
1683
1683
  /*! no static exports found */
1684
1684
  /***/ (function(module, exports, __webpack_require__) {
1685
1685
 
1686
- module.exports = __webpack_require__(/*! C:\Users\Aliaksei_Manetau\WebstormProjects\uui\uui-db\index.tsx */"./index.tsx");
1686
+ module.exports = __webpack_require__(/*! /Users/Aliaksei_Manetau/WebstormProjects/uui/uui-db/index.tsx */"./index.tsx");
1687
1687
 
1688
1688
 
1689
1689
  /***/ }),