@aws-amplify/datastore 5.0.1-api-v6-models.c1977f8.0 → 5.0.1-api-v6-models.891fe0d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/lib/authModeStrategies/defaultAuthStrategy.js +1 -1
  2. package/lib/authModeStrategies/multiAuthStrategy.js +29 -105
  3. package/lib/datastore/datastore.js +887 -1370
  4. package/lib/index.js +1 -1
  5. package/lib/predicates/index.js +53 -102
  6. package/lib/predicates/next.js +310 -557
  7. package/lib/predicates/sort.js +24 -27
  8. package/lib/ssr/index.js +1 -1
  9. package/lib/storage/adapter/AsyncStorageAdapter.js +115 -449
  10. package/lib/storage/adapter/AsyncStorageDatabase.js +215 -480
  11. package/lib/storage/adapter/InMemoryStore.js +27 -101
  12. package/lib/storage/adapter/InMemoryStore.native.js +1 -1
  13. package/lib/storage/adapter/IndexedDBAdapter.js +441 -1002
  14. package/lib/storage/adapter/StorageAdapterBase.js +177 -396
  15. package/lib/storage/adapter/getDefaultAdapter/index.js +5 -6
  16. package/lib/storage/adapter/getDefaultAdapter/index.native.js +2 -2
  17. package/lib/storage/relationship.js +174 -260
  18. package/lib/storage/storage.js +244 -507
  19. package/lib/sync/datastoreConnectivity.js +29 -84
  20. package/lib/sync/datastoreReachability/index.js +1 -1
  21. package/lib/sync/datastoreReachability/index.native.js +2 -2
  22. package/lib/sync/index.js +512 -885
  23. package/lib/sync/merger.js +30 -133
  24. package/lib/sync/outbox.js +147 -302
  25. package/lib/sync/processors/errorMaps.js +30 -80
  26. package/lib/sync/processors/mutation.js +331 -579
  27. package/lib/sync/processors/subscription.js +268 -428
  28. package/lib/sync/processors/sync.js +276 -464
  29. package/lib/sync/utils.js +248 -393
  30. package/lib/tsconfig.tsbuildinfo +1 -1
  31. package/lib/types.js +16 -58
  32. package/lib/util.js +335 -575
  33. package/lib-esm/authModeStrategies/defaultAuthStrategy.js +1 -1
  34. package/lib-esm/authModeStrategies/multiAuthStrategy.js +27 -103
  35. package/lib-esm/datastore/datastore.js +874 -1359
  36. package/lib-esm/index.js +6 -6
  37. package/lib-esm/predicates/index.js +54 -104
  38. package/lib-esm/predicates/next.js +306 -555
  39. package/lib-esm/predicates/sort.js +24 -27
  40. package/lib-esm/ssr/index.js +1 -1
  41. package/lib-esm/storage/adapter/AsyncStorageAdapter.js +111 -446
  42. package/lib-esm/storage/adapter/AsyncStorageDatabase.js +212 -477
  43. package/lib-esm/storage/adapter/InMemoryStore.js +27 -102
  44. package/lib-esm/storage/adapter/IndexedDBAdapter.js +436 -997
  45. package/lib-esm/storage/adapter/StorageAdapterBase.js +172 -392
  46. package/lib-esm/storage/adapter/getDefaultAdapter/index.js +2 -3
  47. package/lib-esm/storage/adapter/getDefaultAdapter/index.native.js +1 -1
  48. package/lib-esm/storage/relationship.js +173 -260
  49. package/lib-esm/storage/storage.js +236 -499
  50. package/lib-esm/sync/datastoreConnectivity.js +26 -82
  51. package/lib-esm/sync/datastoreReachability/index.js +1 -1
  52. package/lib-esm/sync/datastoreReachability/index.native.js +1 -1
  53. package/lib-esm/sync/index.js +498 -872
  54. package/lib-esm/sync/merger.js +28 -131
  55. package/lib-esm/sync/outbox.js +143 -298
  56. package/lib-esm/sync/processors/errorMaps.js +32 -82
  57. package/lib-esm/sync/processors/mutation.js +324 -572
  58. package/lib-esm/sync/processors/subscription.js +258 -418
  59. package/lib-esm/sync/processors/sync.js +269 -457
  60. package/lib-esm/sync/utils.js +245 -390
  61. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  62. package/lib-esm/types.js +16 -59
  63. package/lib-esm/util.js +335 -577
  64. package/package.json +12 -12
  65. package/src/datastore/datastore.ts +4 -3
  66. package/src/storage/adapter/getDefaultAdapter/index.ts +1 -3
  67. package/src/sync/processors/mutation.ts +1 -1
  68. package/src/sync/processors/sync.ts +1 -1
  69. package/src/sync/utils.ts +1 -1
  70. package/src/util.ts +44 -6
@@ -1,77 +1,14 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __values = (this && this.__values) || function(o) {
39
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
- if (m) return m.call(o);
41
- if (o && typeof o.length === "number") return {
42
- next: function () {
43
- if (o && i >= o.length) o = void 0;
44
- return { value: o && o[i++], done: !o };
45
- }
46
- };
47
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
2
  Object.defineProperty(exports, "__esModule", { value: true });
66
- var types_1 = require("../../types");
67
- var util_1 = require("../../util");
68
- var InMemoryStore_1 = require("./InMemoryStore");
69
- var DB_NAME = '@AmplifyDatastore';
70
- var COLLECTION = 'Collection';
71
- var DATA = 'Data';
72
- var monotonicFactoriesMap = new Map();
73
- var AsyncStorageDatabase = /** @class */ (function () {
74
- function AsyncStorageDatabase() {
3
+ const types_1 = require("../../types");
4
+ const util_1 = require("../../util");
5
+ const InMemoryStore_1 = require("./InMemoryStore");
6
+ const DB_NAME = '@AmplifyDatastore';
7
+ const COLLECTION = 'Collection';
8
+ const DATA = 'Data';
9
+ const monotonicFactoriesMap = new Map();
10
+ class AsyncStorageDatabase {
11
+ constructor() {
75
12
  /**
76
13
  * Maps storeNames to a map of ulid->id
77
14
  */
@@ -83,444 +20,242 @@ var AsyncStorageDatabase = /** @class */ (function () {
83
20
  * @param storeName {string} - Name of the store
84
21
  * @returns Map of ulid->id
85
22
  */
86
- AsyncStorageDatabase.prototype.getCollectionIndex = function (storeName) {
23
+ getCollectionIndex(storeName) {
87
24
  if (!this._collectionInMemoryIndex.has(storeName)) {
88
25
  this._collectionInMemoryIndex.set(storeName, new Map());
89
26
  }
90
27
  return this._collectionInMemoryIndex.get(storeName);
91
- };
28
+ }
92
29
  /**
93
30
  * Return ULID for store if it exists, otherwise create a new one
94
31
  * @param storeName {string} - Name of the store
95
32
  * @returns ulid
96
33
  */
97
- AsyncStorageDatabase.prototype.getMonotonicFactory = function (storeName) {
34
+ getMonotonicFactory(storeName) {
98
35
  if (!monotonicFactoriesMap.has(storeName)) {
99
36
  monotonicFactoriesMap.set(storeName, (0, util_1.monotonicUlidFactory)());
100
37
  }
101
38
  return monotonicFactoriesMap.get(storeName);
102
- };
103
- AsyncStorageDatabase.prototype.init = function () {
104
- return __awaiter(this, void 0, void 0, function () {
105
- var allKeys, keysForCollectionEntries, allKeys_1, allKeys_1_1, key, _a, dbName, storeName, recordType, ulidOrId, id, ulid, id_1, newUlid, oldKey, newKey, item, e_1_1;
106
- var e_1, _b;
107
- return __generator(this, function (_c) {
108
- switch (_c.label) {
109
- case 0:
110
- this._collectionInMemoryIndex.clear();
111
- return [4 /*yield*/, this.storage.getAllKeys()];
112
- case 1:
113
- allKeys = _c.sent();
114
- keysForCollectionEntries = [];
115
- _c.label = 2;
116
- case 2:
117
- _c.trys.push([2, 12, 13, 14]);
118
- allKeys_1 = __values(allKeys), allKeys_1_1 = allKeys_1.next();
119
- _c.label = 3;
120
- case 3:
121
- if (!!allKeys_1_1.done) return [3 /*break*/, 11];
122
- key = allKeys_1_1.value;
123
- _a = __read(key.split('::'), 5), dbName = _a[0], storeName = _a[1], recordType = _a[2], ulidOrId = _a[3], id = _a[4];
124
- if (!(dbName === DB_NAME)) return [3 /*break*/, 10];
125
- if (!(recordType === DATA)) return [3 /*break*/, 9];
126
- ulid = void 0;
127
- if (!(id === undefined)) return [3 /*break*/, 7];
128
- id_1 = ulidOrId;
129
- newUlid = this.getMonotonicFactory(storeName)();
130
- oldKey = this.getLegacyKeyForItem(storeName, id_1);
131
- newKey = this.getKeyForItem(storeName, id_1, newUlid);
132
- return [4 /*yield*/, this.storage.getItem(oldKey)];
133
- case 4:
134
- item = _c.sent();
135
- return [4 /*yield*/, this.storage.setItem(newKey, item)];
136
- case 5:
137
- _c.sent();
138
- return [4 /*yield*/, this.storage.removeItem(oldKey)];
139
- case 6:
140
- _c.sent();
39
+ }
40
+ async init() {
41
+ this._collectionInMemoryIndex.clear();
42
+ const allKeys = await this.storage.getAllKeys();
43
+ const keysForCollectionEntries = [];
44
+ for (const key of allKeys) {
45
+ const [dbName, storeName, recordType, ulidOrId, id] = key.split('::');
46
+ if (dbName === DB_NAME) {
47
+ if (recordType === DATA) {
48
+ let ulid;
49
+ if (id === undefined) {
50
+ // It is an old entry (without ulid). Need to migrate to new key format
51
+ const id = ulidOrId;
52
+ const newUlid = this.getMonotonicFactory(storeName)();
53
+ const oldKey = this.getLegacyKeyForItem(storeName, id);
54
+ const newKey = this.getKeyForItem(storeName, id, newUlid);
55
+ const item = await this.storage.getItem(oldKey);
56
+ await this.storage.setItem(newKey, item);
57
+ await this.storage.removeItem(oldKey);
141
58
  ulid = newUlid;
142
- return [3 /*break*/, 8];
143
- case 7:
59
+ }
60
+ else {
144
61
  ulid = ulidOrId;
145
- _c.label = 8;
146
- case 8:
147
- this.getCollectionIndex(storeName).set(id, ulid);
148
- return [3 /*break*/, 10];
149
- case 9:
150
- if (recordType === COLLECTION) {
151
- keysForCollectionEntries.push(key);
152
- }
153
- _c.label = 10;
154
- case 10:
155
- allKeys_1_1 = allKeys_1.next();
156
- return [3 /*break*/, 3];
157
- case 11: return [3 /*break*/, 14];
158
- case 12:
159
- e_1_1 = _c.sent();
160
- e_1 = { error: e_1_1 };
161
- return [3 /*break*/, 14];
162
- case 13:
163
- try {
164
- if (allKeys_1_1 && !allKeys_1_1.done && (_b = allKeys_1.return)) _b.call(allKeys_1);
165
- }
166
- finally { if (e_1) throw e_1.error; }
167
- return [7 /*endfinally*/];
168
- case 14:
169
- if (!(keysForCollectionEntries.length > 0)) return [3 /*break*/, 16];
170
- return [4 /*yield*/, this.storage.multiRemove(keysForCollectionEntries)];
171
- case 15:
172
- _c.sent();
173
- _c.label = 16;
174
- case 16: return [2 /*return*/];
62
+ }
63
+ this.getCollectionIndex(storeName).set(id, ulid);
175
64
  }
176
- });
177
- });
178
- };
179
- AsyncStorageDatabase.prototype.save = function (item, storeName, keys, keyValuesPath) {
180
- var _a, _b;
181
- return __awaiter(this, void 0, void 0, function () {
182
- var idxName, ulid, itemKey;
183
- return __generator(this, function (_c) {
184
- switch (_c.label) {
185
- case 0:
186
- idxName = (0, util_1.indexNameFromKeys)(keys);
187
- ulid = ((_a = this.getCollectionIndex(storeName)) === null || _a === void 0 ? void 0 : _a.get(idxName)) ||
188
- this.getMonotonicFactory(storeName)();
189
- itemKey = this.getKeyForItem(storeName, keyValuesPath, ulid);
190
- // Set key in collection index
191
- (_b = this.getCollectionIndex(storeName)) === null || _b === void 0 ? void 0 : _b.set(keyValuesPath, ulid);
192
- // Save item in db
193
- return [4 /*yield*/, this.storage.setItem(itemKey, JSON.stringify(item))];
194
- case 1:
195
- // Save item in db
196
- _c.sent();
197
- return [2 /*return*/];
65
+ else if (recordType === COLLECTION) {
66
+ keysForCollectionEntries.push(key);
198
67
  }
68
+ }
69
+ }
70
+ if (keysForCollectionEntries.length > 0) {
71
+ await this.storage.multiRemove(keysForCollectionEntries);
72
+ }
73
+ }
74
+ async save(item, storeName, keys, keyValuesPath) {
75
+ const idxName = (0, util_1.indexNameFromKeys)(keys);
76
+ const ulid = this.getCollectionIndex(storeName)?.get(idxName) ||
77
+ this.getMonotonicFactory(storeName)();
78
+ // Retrieve db key for item
79
+ const itemKey = this.getKeyForItem(storeName, keyValuesPath, ulid);
80
+ // Set key in collection index
81
+ this.getCollectionIndex(storeName)?.set(keyValuesPath, ulid);
82
+ // Save item in db
83
+ await this.storage.setItem(itemKey, JSON.stringify(item));
84
+ }
85
+ async batchSave(storeName, items, keys) {
86
+ if (items.length === 0) {
87
+ return [];
88
+ }
89
+ const result = [];
90
+ const collection = this.getCollectionIndex(storeName);
91
+ const keysToDelete = new Set();
92
+ const keysToSave = new Set();
93
+ const allItemsKeys = [];
94
+ const itemsMap = {};
95
+ /* Populate allItemKeys, keysToDelete, and keysToSave */
96
+ for (const item of items) {
97
+ // Extract keys from concatenated key path, map to item values
98
+ const keyValues = keys.map(field => item[field]);
99
+ const { _deleted } = item;
100
+ // If id is in the store, retrieve, otherwise generate new ULID
101
+ const ulid = collection.get(keyValues.join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR)) ||
102
+ this.getMonotonicFactory(storeName)();
103
+ // Generate the "longer key" for the item
104
+ const key = this.getKeyForItem(storeName, keyValues.join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR), ulid);
105
+ allItemsKeys.push(key);
106
+ itemsMap[key] = { ulid, model: item };
107
+ if (_deleted) {
108
+ keysToDelete.add(key);
109
+ }
110
+ else {
111
+ keysToSave.add(key);
112
+ }
113
+ }
114
+ const existingRecordsMap = await this.storage.multiGet(allItemsKeys);
115
+ const existingRecordsKeys = existingRecordsMap
116
+ .filter(([, v]) => !!v)
117
+ .reduce((set, [k]) => set.add(k), new Set());
118
+ // Delete
119
+ await new Promise((resolve, reject) => {
120
+ if (keysToDelete.size === 0) {
121
+ resolve();
122
+ return;
123
+ }
124
+ const keysToDeleteArray = Array.from(keysToDelete);
125
+ keysToDeleteArray.forEach(key => {
126
+ // key: full db key
127
+ // keys: PK and/or SK keys
128
+ const primaryKeyValues = keys
129
+ .map(field => itemsMap[key].model[field])
130
+ .join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR);
131
+ collection.delete(primaryKeyValues);
199
132
  });
200
- });
201
- };
202
- AsyncStorageDatabase.prototype.batchSave = function (storeName, items, keys) {
203
- return __awaiter(this, void 0, void 0, function () {
204
- var result, collection, keysToDelete, keysToSave, allItemsKeys, itemsMap, _loop_1, this_1, items_1, items_1_1, item, existingRecordsMap, existingRecordsKeys, allItemsKeys_1, allItemsKeys_1_1, key;
205
- var e_2, _a, e_3, _b;
206
- var _this = this;
207
- return __generator(this, function (_c) {
208
- switch (_c.label) {
209
- case 0:
210
- if (items.length === 0) {
211
- return [2 /*return*/, []];
212
- }
213
- result = [];
214
- collection = this.getCollectionIndex(storeName);
215
- keysToDelete = new Set();
216
- keysToSave = new Set();
217
- allItemsKeys = [];
218
- itemsMap = {};
219
- _loop_1 = function (item) {
220
- // Extract keys from concatenated key path, map to item values
221
- var keyValues = keys.map(function (field) { return item[field]; });
222
- var _deleted = item._deleted;
223
- // If id is in the store, retrieve, otherwise generate new ULID
224
- var ulid = collection.get(keyValues.join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR)) ||
225
- this_1.getMonotonicFactory(storeName)();
226
- // Generate the "longer key" for the item
227
- var key = this_1.getKeyForItem(storeName, keyValues.join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR), ulid);
228
- allItemsKeys.push(key);
229
- itemsMap[key] = { ulid: ulid, model: item };
230
- if (_deleted) {
231
- keysToDelete.add(key);
232
- }
233
- else {
234
- keysToSave.add(key);
235
- }
236
- };
237
- this_1 = this;
238
- try {
239
- /* Populate allItemKeys, keysToDelete, and keysToSave */
240
- for (items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
241
- item = items_1_1.value;
242
- _loop_1(item);
243
- }
244
- }
245
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
246
- finally {
247
- try {
248
- if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
249
- }
250
- finally { if (e_2) throw e_2.error; }
251
- }
252
- return [4 /*yield*/, this.storage.multiGet(allItemsKeys)];
253
- case 1:
254
- existingRecordsMap = _c.sent();
255
- existingRecordsKeys = existingRecordsMap
256
- .filter(function (_a) {
257
- var _b = __read(_a, 2), v = _b[1];
258
- return !!v;
259
- })
260
- .reduce(function (set, _a) {
261
- var _b = __read(_a, 1), k = _b[0];
262
- return set.add(k);
263
- }, new Set());
264
- // Delete
265
- return [4 /*yield*/, new Promise(function (resolve, reject) {
266
- if (keysToDelete.size === 0) {
267
- resolve();
268
- return;
269
- }
270
- var keysToDeleteArray = Array.from(keysToDelete);
271
- keysToDeleteArray.forEach(function (key) {
272
- // key: full db key
273
- // keys: PK and/or SK keys
274
- var primaryKeyValues = keys
275
- .map(function (field) { return itemsMap[key].model[field]; })
276
- .join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR);
277
- collection.delete(primaryKeyValues);
278
- });
279
- _this.storage.multiRemove(keysToDeleteArray, function (errors) {
280
- if (errors && errors.length > 0) {
281
- reject(errors);
282
- }
283
- else {
284
- resolve();
285
- }
286
- });
287
- })];
288
- case 2:
289
- // Delete
290
- _c.sent();
291
- // Save
292
- return [4 /*yield*/, new Promise(function (resolve, reject) {
293
- if (keysToSave.size === 0) {
294
- resolve();
295
- return;
296
- }
297
- var entriesToSet = Array.from(keysToSave).map(function (key) { return [
298
- key,
299
- JSON.stringify(itemsMap[key].model),
300
- ]; });
301
- keysToSave.forEach(function (key) {
302
- var _a = itemsMap[key], model = _a.model, ulid = _a.ulid;
303
- // Retrieve values from model, use as key for collection index
304
- var keyValues = keys
305
- .map(function (field) { return model[field]; })
306
- .join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR);
307
- collection.set(keyValues, ulid);
308
- });
309
- _this.storage.multiSet(entriesToSet, function (errors) {
310
- if (errors && errors.length > 0) {
311
- reject(errors);
312
- }
313
- else {
314
- resolve();
315
- }
316
- });
317
- })];
318
- case 3:
319
- // Save
320
- _c.sent();
321
- try {
322
- for (allItemsKeys_1 = __values(allItemsKeys), allItemsKeys_1_1 = allItemsKeys_1.next(); !allItemsKeys_1_1.done; allItemsKeys_1_1 = allItemsKeys_1.next()) {
323
- key = allItemsKeys_1_1.value;
324
- if (keysToDelete.has(key) && existingRecordsKeys.has(key)) {
325
- result.push([itemsMap[key].model, types_1.OpType.DELETE]);
326
- }
327
- else if (keysToSave.has(key)) {
328
- result.push([
329
- itemsMap[key].model,
330
- existingRecordsKeys.has(key) ? types_1.OpType.UPDATE : types_1.OpType.INSERT,
331
- ]);
332
- }
333
- }
334
- }
335
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
336
- finally {
337
- try {
338
- if (allItemsKeys_1_1 && !allItemsKeys_1_1.done && (_b = allItemsKeys_1.return)) _b.call(allItemsKeys_1);
339
- }
340
- finally { if (e_3) throw e_3.error; }
341
- }
342
- return [2 /*return*/, result];
133
+ this.storage.multiRemove(keysToDeleteArray, (errors) => {
134
+ if (errors && errors.length > 0) {
135
+ reject(errors);
343
136
  }
344
- });
345
- });
346
- };
347
- AsyncStorageDatabase.prototype.get = function (keyValuePath, storeName) {
348
- return __awaiter(this, void 0, void 0, function () {
349
- var ulid, itemKey, recordAsString, record;
350
- return __generator(this, function (_a) {
351
- switch (_a.label) {
352
- case 0:
353
- ulid = this.getCollectionIndex(storeName).get(keyValuePath);
354
- itemKey = this.getKeyForItem(storeName, keyValuePath, ulid);
355
- return [4 /*yield*/, this.storage.getItem(itemKey)];
356
- case 1:
357
- recordAsString = _a.sent();
358
- record = recordAsString && JSON.parse(recordAsString);
359
- return [2 /*return*/, record];
137
+ else {
138
+ resolve();
360
139
  }
361
140
  });
362
141
  });
363
- };
364
- AsyncStorageDatabase.prototype.getOne = function (firstOrLast, storeName) {
365
- return __awaiter(this, void 0, void 0, function () {
366
- var collection, _a, itemId, ulid, itemKey, itemString, _b, result;
367
- return __generator(this, function (_c) {
368
- switch (_c.label) {
369
- case 0:
370
- collection = this.getCollectionIndex(storeName);
371
- _a = __read(firstOrLast === types_1.QueryOne.FIRST
372
- ? (function () {
373
- var e_4, _a, _b;
374
- var id, ulid;
375
- try {
376
- for (var collection_1 = __values(collection), collection_1_1 = collection_1.next(); !collection_1_1.done; collection_1_1 = collection_1.next()) {
377
- _b = __read(collection_1_1.value, 2), id = _b[0], ulid = _b[1];
378
- break;
379
- } // Get first element of the set
380
- }
381
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
382
- finally {
383
- try {
384
- if (collection_1_1 && !collection_1_1.done && (_a = collection_1.return)) _a.call(collection_1);
385
- }
386
- finally { if (e_4) throw e_4.error; }
387
- }
388
- return [id, ulid];
389
- })()
390
- : (function () {
391
- var e_5, _a, _b;
392
- var id, ulid;
393
- try {
394
- for (var collection_2 = __values(collection), collection_2_1 = collection_2.next(); !collection_2_1.done; collection_2_1 = collection_2.next()) {
395
- _b = __read(collection_2_1.value, 2), id = _b[0], ulid = _b[1];
396
- ;
397
- } // Get last element of the set
398
- }
399
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
400
- finally {
401
- try {
402
- if (collection_2_1 && !collection_2_1.done && (_a = collection_2.return)) _a.call(collection_2);
403
- }
404
- finally { if (e_5) throw e_5.error; }
405
- }
406
- return [id, ulid];
407
- })(), 2), itemId = _a[0], ulid = _a[1];
408
- itemKey = this.getKeyForItem(storeName, itemId, ulid);
409
- _b = itemKey;
410
- if (!_b) return [3 /*break*/, 2];
411
- return [4 /*yield*/, this.storage.getItem(itemKey)];
412
- case 1:
413
- _b = (_c.sent());
414
- _c.label = 2;
415
- case 2:
416
- itemString = _b;
417
- result = itemString ? JSON.parse(itemString) || undefined : undefined;
418
- return [2 /*return*/, result];
142
+ // Save
143
+ await new Promise((resolve, reject) => {
144
+ if (keysToSave.size === 0) {
145
+ resolve();
146
+ return;
147
+ }
148
+ const entriesToSet = Array.from(keysToSave).map(key => [
149
+ key,
150
+ JSON.stringify(itemsMap[key].model),
151
+ ]);
152
+ keysToSave.forEach(key => {
153
+ const { model, ulid } = itemsMap[key];
154
+ // Retrieve values from model, use as key for collection index
155
+ const keyValues = keys
156
+ .map(field => model[field])
157
+ .join(util_1.DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR);
158
+ collection.set(keyValues, ulid);
159
+ });
160
+ this.storage.multiSet(entriesToSet, (errors) => {
161
+ if (errors && errors.length > 0) {
162
+ reject(errors);
163
+ }
164
+ else {
165
+ resolve();
419
166
  }
420
167
  });
421
168
  });
422
- };
169
+ for (const key of allItemsKeys) {
170
+ if (keysToDelete.has(key) && existingRecordsKeys.has(key)) {
171
+ result.push([itemsMap[key].model, types_1.OpType.DELETE]);
172
+ }
173
+ else if (keysToSave.has(key)) {
174
+ result.push([
175
+ itemsMap[key].model,
176
+ existingRecordsKeys.has(key) ? types_1.OpType.UPDATE : types_1.OpType.INSERT,
177
+ ]);
178
+ }
179
+ }
180
+ return result;
181
+ }
182
+ async get(keyValuePath, storeName) {
183
+ const ulid = this.getCollectionIndex(storeName).get(keyValuePath);
184
+ const itemKey = this.getKeyForItem(storeName, keyValuePath, ulid);
185
+ const recordAsString = await this.storage.getItem(itemKey);
186
+ const record = recordAsString && JSON.parse(recordAsString);
187
+ return record;
188
+ }
189
+ async getOne(firstOrLast, storeName) {
190
+ const collection = this.getCollectionIndex(storeName);
191
+ const [itemId, ulid] = firstOrLast === types_1.QueryOne.FIRST
192
+ ? (() => {
193
+ let id, ulid;
194
+ for ([id, ulid] of collection)
195
+ break; // Get first element of the set
196
+ return [id, ulid];
197
+ })()
198
+ : (() => {
199
+ let id, ulid;
200
+ for ([id, ulid] of collection)
201
+ ; // Get last element of the set
202
+ return [id, ulid];
203
+ })();
204
+ const itemKey = this.getKeyForItem(storeName, itemId, ulid);
205
+ const itemString = itemKey && (await this.storage.getItem(itemKey));
206
+ const result = itemString ? JSON.parse(itemString) || undefined : undefined;
207
+ return result;
208
+ }
423
209
  /**
424
210
  * This function gets all the records stored in async storage for a particular storeName
425
211
  * It then loads all the records for that filtered set of keys using multiGet()
426
212
  */
427
- AsyncStorageDatabase.prototype.getAll = function (storeName, pagination) {
428
- return __awaiter(this, void 0, void 0, function () {
429
- var collection, _a, _b, page, _c, limit, start, end, keysForStore, count, collection_3, collection_3_1, _d, id, ulid, storeRecordStrings, records;
430
- var e_6, _e;
431
- return __generator(this, function (_f) {
432
- switch (_f.label) {
433
- case 0:
434
- collection = this.getCollectionIndex(storeName);
435
- _a = pagination || {}, _b = _a.page, page = _b === void 0 ? 0 : _b, _c = _a.limit, limit = _c === void 0 ? 0 : _c;
436
- start = Math.max(0, page * limit) || 0;
437
- end = limit > 0 ? start + limit : undefined;
438
- keysForStore = [];
439
- count = 0;
440
- try {
441
- for (collection_3 = __values(collection), collection_3_1 = collection_3.next(); !collection_3_1.done; collection_3_1 = collection_3.next()) {
442
- _d = __read(collection_3_1.value, 2), id = _d[0], ulid = _d[1];
443
- count++;
444
- if (count <= start) {
445
- continue;
446
- }
447
- keysForStore.push(this.getKeyForItem(storeName, id, ulid));
448
- if (count === end) {
449
- break;
450
- }
451
- }
452
- }
453
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
454
- finally {
455
- try {
456
- if (collection_3_1 && !collection_3_1.done && (_e = collection_3.return)) _e.call(collection_3);
457
- }
458
- finally { if (e_6) throw e_6.error; }
459
- }
460
- return [4 /*yield*/, this.storage.multiGet(keysForStore)];
461
- case 1:
462
- storeRecordStrings = _f.sent();
463
- records = storeRecordStrings
464
- .filter(function (_a) {
465
- var _b = __read(_a, 2), value = _b[1];
466
- return value;
467
- })
468
- .map(function (_a) {
469
- var _b = __read(_a, 2), value = _b[1];
470
- return JSON.parse(value);
471
- });
472
- return [2 /*return*/, records];
473
- }
474
- });
475
- });
476
- };
477
- AsyncStorageDatabase.prototype.delete = function (key, storeName) {
478
- return __awaiter(this, void 0, void 0, function () {
479
- var ulid, itemKey;
480
- return __generator(this, function (_a) {
481
- switch (_a.label) {
482
- case 0:
483
- ulid = this.getCollectionIndex(storeName).get(key);
484
- itemKey = this.getKeyForItem(storeName, key, ulid);
485
- this.getCollectionIndex(storeName).delete(key);
486
- return [4 /*yield*/, this.storage.removeItem(itemKey)];
487
- case 1:
488
- _a.sent();
489
- return [2 /*return*/];
490
- }
491
- });
492
- });
493
- };
213
+ async getAll(storeName, pagination) {
214
+ const collection = this.getCollectionIndex(storeName);
215
+ const { page = 0, limit = 0 } = pagination || {};
216
+ const start = Math.max(0, page * limit) || 0;
217
+ const end = limit > 0 ? start + limit : undefined;
218
+ const keysForStore = [];
219
+ let count = 0;
220
+ for (const [id, ulid] of collection) {
221
+ count++;
222
+ if (count <= start) {
223
+ continue;
224
+ }
225
+ keysForStore.push(this.getKeyForItem(storeName, id, ulid));
226
+ if (count === end) {
227
+ break;
228
+ }
229
+ }
230
+ const storeRecordStrings = await this.storage.multiGet(keysForStore);
231
+ const records = storeRecordStrings
232
+ .filter(([, value]) => value)
233
+ .map(([, value]) => JSON.parse(value));
234
+ return records;
235
+ }
236
+ async delete(key, storeName) {
237
+ const ulid = this.getCollectionIndex(storeName).get(key);
238
+ const itemKey = this.getKeyForItem(storeName, key, ulid);
239
+ this.getCollectionIndex(storeName).delete(key);
240
+ await this.storage.removeItem(itemKey);
241
+ }
494
242
  /**
495
243
  * Clear the AsyncStorage of all DataStore entries
496
244
  */
497
- AsyncStorageDatabase.prototype.clear = function () {
498
- return __awaiter(this, void 0, void 0, function () {
499
- var allKeys, allDataStoreKeys;
500
- return __generator(this, function (_a) {
501
- switch (_a.label) {
502
- case 0: return [4 /*yield*/, this.storage.getAllKeys()];
503
- case 1:
504
- allKeys = _a.sent();
505
- allDataStoreKeys = allKeys.filter(function (key) { return key.startsWith(DB_NAME); });
506
- return [4 /*yield*/, this.storage.multiRemove(allDataStoreKeys)];
507
- case 2:
508
- _a.sent();
509
- this._collectionInMemoryIndex.clear();
510
- return [2 /*return*/];
511
- }
512
- });
513
- });
514
- };
515
- AsyncStorageDatabase.prototype.getKeyForItem = function (storeName, id, ulid) {
516
- return "".concat(this.getKeyPrefixForStoreItems(storeName), "::").concat(ulid, "::").concat(id);
517
- };
518
- AsyncStorageDatabase.prototype.getLegacyKeyForItem = function (storeName, id) {
519
- return "".concat(this.getKeyPrefixForStoreItems(storeName), "::").concat(id);
520
- };
521
- AsyncStorageDatabase.prototype.getKeyPrefixForStoreItems = function (storeName) {
522
- return "".concat(DB_NAME, "::").concat(storeName, "::").concat(DATA);
523
- };
524
- return AsyncStorageDatabase;
525
- }());
245
+ async clear() {
246
+ const allKeys = await this.storage.getAllKeys();
247
+ const allDataStoreKeys = allKeys.filter(key => key.startsWith(DB_NAME));
248
+ await this.storage.multiRemove(allDataStoreKeys);
249
+ this._collectionInMemoryIndex.clear();
250
+ }
251
+ getKeyForItem(storeName, id, ulid) {
252
+ return `${this.getKeyPrefixForStoreItems(storeName)}::${ulid}::${id}`;
253
+ }
254
+ getLegacyKeyForItem(storeName, id) {
255
+ return `${this.getKeyPrefixForStoreItems(storeName)}::${id}`;
256
+ }
257
+ getKeyPrefixForStoreItems(storeName) {
258
+ return `${DB_NAME}::${storeName}::${DATA}`;
259
+ }
260
+ }
526
261
  exports.default = AsyncStorageDatabase;