UNPKG

33.9 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
6 * the License. A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0/
9 *
10 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
12 * and limitations under the License.
13 */
14var __extends = (this && this.__extends) || (function () {
15 var extendStatics = function (d, b) {
16 extendStatics = Object.setPrototypeOf ||
17 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
18 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
19 return extendStatics(d, b);
20 };
21 return function (d, b) {
22 extendStatics(d, b);
23 function __() { this.constructor = d; }
24 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25 };
26})();
27var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
28 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29 return new (P || (P = Promise))(function (resolve, reject) {
30 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33 step((generator = generator.apply(thisArg, _arguments || [])).next());
34 });
35};
36var __generator = (this && this.__generator) || function (thisArg, body) {
37 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
38 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39 function verb(n) { return function (v) { return step([n, v]); }; }
40 function step(op) {
41 if (f) throw new TypeError("Generator is already executing.");
42 while (_) try {
43 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;
44 if (y = 0, t) op = [op[0] & 2, t.value];
45 switch (op[0]) {
46 case 0: case 1: t = op; break;
47 case 4: _.label++; return { value: op[1], done: false };
48 case 5: _.label++; y = op[1]; op = [0]; continue;
49 case 7: op = _.ops.pop(); _.trys.pop(); continue;
50 default:
51 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55 if (t[2]) _.ops.pop();
56 _.trys.pop(); continue;
57 }
58 op = body.call(thisArg, _);
59 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61 }
62};
63Object.defineProperty(exports, "__esModule", { value: true });
64var StorageCache_1 = require("./StorageCache");
65var Utils_1 = require("./Utils");
66var react_native_1 = require("react-native");
67exports.AsyncStorage = react_native_1.AsyncStorage;
68var core_1 = require("@aws-amplify/core");
69var logger = new core_1.ConsoleLogger('AsyncStorageCache');
70/*
71 * Customized cache which based on the AsyncStorage with LRU implemented
72 */
73var AsyncStorageCache = /** @class */ (function (_super) {
74 __extends(AsyncStorageCache, _super);
75 /**
76 * initialize the cache
77 *
78 * @param {Object} config - the configuration of the cache
79 */
80 function AsyncStorageCache(config) {
81 var _this = this;
82 var cache_config = config
83 ? Object.assign({}, Utils_1.defaultConfig, config)
84 : Utils_1.defaultConfig;
85 _this = _super.call(this, cache_config) || this;
86 _this.getItem = _this.getItem.bind(_this);
87 _this.setItem = _this.setItem.bind(_this);
88 _this.removeItem = _this.removeItem.bind(_this);
89 logger.debug('Using AsyncStorageCache');
90 return _this;
91 }
92 /**
93 * decrease current size of the cache
94 * @private
95 * @param amount - the amount of the cache size which needs to be decreased
96 */
97 AsyncStorageCache.prototype._decreaseCurSizeInBytes = function (amount) {
98 return __awaiter(this, void 0, void 0, function () {
99 var curSize;
100 return __generator(this, function (_a) {
101 switch (_a.label) {
102 case 0: return [4 /*yield*/, this.getCacheCurSize()];
103 case 1:
104 curSize = _a.sent();
105 return [4 /*yield*/, react_native_1.AsyncStorage.setItem(this.cacheCurSizeKey, (curSize - amount).toString())];
106 case 2:
107 _a.sent();
108 return [2 /*return*/];
109 }
110 });
111 });
112 };
113 /**
114 * increase current size of the cache
115 * @private
116 * @param amount - the amount of the cache szie which need to be increased
117 */
118 AsyncStorageCache.prototype._increaseCurSizeInBytes = function (amount) {
119 return __awaiter(this, void 0, void 0, function () {
120 var curSize;
121 return __generator(this, function (_a) {
122 switch (_a.label) {
123 case 0: return [4 /*yield*/, this.getCacheCurSize()];
124 case 1:
125 curSize = _a.sent();
126 return [4 /*yield*/, react_native_1.AsyncStorage.setItem(this.cacheCurSizeKey, (curSize + amount).toString())];
127 case 2:
128 _a.sent();
129 return [2 /*return*/];
130 }
131 });
132 });
133 };
134 /**
135 * update the visited time if item has been visited
136 * @private
137 * @param item - the item which need to be refreshed
138 * @param prefixedKey - the key of the item
139 *
140 * @return the refreshed item
141 */
142 AsyncStorageCache.prototype._refreshItem = function (item, prefixedKey) {
143 return __awaiter(this, void 0, void 0, function () {
144 return __generator(this, function (_a) {
145 switch (_a.label) {
146 case 0:
147 item.visitedTime = Utils_1.getCurrTime();
148 return [4 /*yield*/, react_native_1.AsyncStorage.setItem(prefixedKey, JSON.stringify(item))];
149 case 1:
150 _a.sent();
151 return [2 /*return*/, item];
152 }
153 });
154 });
155 };
156 /**
157 * check wether item is expired
158 * @private
159 * @param key - the key of the item
160 *
161 * @return true if the item is expired.
162 */
163 AsyncStorageCache.prototype._isExpired = function (key) {
164 return __awaiter(this, void 0, void 0, function () {
165 var text, item;
166 return __generator(this, function (_a) {
167 switch (_a.label) {
168 case 0: return [4 /*yield*/, react_native_1.AsyncStorage.getItem(key)];
169 case 1:
170 text = _a.sent();
171 item = JSON.parse(text);
172 if (Utils_1.getCurrTime() >= item.expires) {
173 return [2 /*return*/, true];
174 }
175 return [2 /*return*/, false];
176 }
177 });
178 });
179 };
180 /**
181 * delete item from cache
182 * @private
183 * @param prefixedKey - the key of the item
184 * @param size - optional, the byte size of the item
185 */
186 AsyncStorageCache.prototype._removeItem = function (prefixedKey, size) {
187 return __awaiter(this, void 0, void 0, function () {
188 var itemSize, _a, _b, _c, removeItemError_1;
189 return __generator(this, function (_d) {
190 switch (_d.label) {
191 case 0:
192 if (!size) return [3 /*break*/, 1];
193 _a = size;
194 return [3 /*break*/, 3];
195 case 1:
196 _c = (_b = JSON).parse;
197 return [4 /*yield*/, react_native_1.AsyncStorage.getItem(prefixedKey)];
198 case 2:
199 _a = _c.apply(_b, [_d.sent()]).byteSize;
200 _d.label = 3;
201 case 3:
202 itemSize = _a;
203 // first try to update the current size of the cache
204 return [4 /*yield*/, this._decreaseCurSizeInBytes(itemSize)];
205 case 4:
206 // first try to update the current size of the cache
207 _d.sent();
208 _d.label = 5;
209 case 5:
210 _d.trys.push([5, 7, , 9]);
211 return [4 /*yield*/, react_native_1.AsyncStorage.removeItem(prefixedKey)];
212 case 6:
213 _d.sent();
214 return [3 /*break*/, 9];
215 case 7:
216 removeItemError_1 = _d.sent();
217 // if some error happened, we need to rollback the current size
218 return [4 /*yield*/, this._increaseCurSizeInBytes(itemSize)];
219 case 8:
220 // if some error happened, we need to rollback the current size
221 _d.sent();
222 logger.error("Failed to remove item: " + removeItemError_1);
223 return [3 /*break*/, 9];
224 case 9: return [2 /*return*/];
225 }
226 });
227 });
228 };
229 /**
230 * put item into cache
231 * @private
232 * @param prefixedKey - the key of the item
233 * @param itemData - the value of the item
234 * @param itemSizeInBytes - the byte size of the item
235 */
236 AsyncStorageCache.prototype._setItem = function (prefixedKey, item) {
237 return __awaiter(this, void 0, void 0, function () {
238 var setItemErr_1;
239 return __generator(this, function (_a) {
240 switch (_a.label) {
241 case 0:
242 // first try to update the current size of the cache.
243 return [4 /*yield*/, this._increaseCurSizeInBytes(item.byteSize)];
244 case 1:
245 // first try to update the current size of the cache.
246 _a.sent();
247 _a.label = 2;
248 case 2:
249 _a.trys.push([2, 4, , 6]);
250 return [4 /*yield*/, react_native_1.AsyncStorage.setItem(prefixedKey, JSON.stringify(item))];
251 case 3:
252 _a.sent();
253 return [3 /*break*/, 6];
254 case 4:
255 setItemErr_1 = _a.sent();
256 // if some error happened, we need to rollback the current size
257 return [4 /*yield*/, this._decreaseCurSizeInBytes(item.byteSize)];
258 case 5:
259 // if some error happened, we need to rollback the current size
260 _a.sent();
261 logger.error("Failed to set item " + setItemErr_1);
262 return [3 /*break*/, 6];
263 case 6: return [2 /*return*/];
264 }
265 });
266 });
267 };
268 /**
269 * total space needed when poping out items
270 * @private
271 * @param itemSize
272 *
273 * @return total space needed
274 */
275 AsyncStorageCache.prototype._sizeToPop = function (itemSize) {
276 return __awaiter(this, void 0, void 0, function () {
277 var spaceItemNeed, cacheThresholdSpace;
278 return __generator(this, function (_a) {
279 switch (_a.label) {
280 case 0: return [4 /*yield*/, this.getCacheCurSize()];
281 case 1:
282 spaceItemNeed = (_a.sent()) + itemSize - this.config.capacityInBytes;
283 cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;
284 return [2 /*return*/, spaceItemNeed > cacheThresholdSpace
285 ? spaceItemNeed
286 : cacheThresholdSpace];
287 }
288 });
289 });
290 };
291 /**
292 * see whether cache is full
293 * @private
294 * @param itemSize
295 *
296 * @return true if cache is full
297 */
298 AsyncStorageCache.prototype._isCacheFull = function (itemSize) {
299 return __awaiter(this, void 0, void 0, function () {
300 var _a;
301 return __generator(this, function (_b) {
302 switch (_b.label) {
303 case 0:
304 _a = itemSize;
305 return [4 /*yield*/, this.getCacheCurSize()];
306 case 1: return [2 /*return*/, (_a + (_b.sent()) > this.config.capacityInBytes)];
307 }
308 });
309 });
310 };
311 /**
312 * scan the storage and find out all the keys owned by this cache
313 * also clean the expired keys while scanning
314 * @private
315 * @return array of keys
316 */
317 AsyncStorageCache.prototype._findValidKeys = function () {
318 return __awaiter(this, void 0, void 0, function () {
319 var keys, keyInCache, i, key;
320 return __generator(this, function (_a) {
321 switch (_a.label) {
322 case 0:
323 keys = [];
324 keyInCache = [];
325 return [4 /*yield*/, react_native_1.AsyncStorage.getAllKeys()];
326 case 1:
327 keyInCache = _a.sent();
328 i = 0;
329 _a.label = 2;
330 case 2:
331 if (!(i < keyInCache.length)) return [3 /*break*/, 7];
332 key = keyInCache[i];
333 if (!(key.indexOf(this.config.keyPrefix) === 0 &&
334 key !== this.cacheCurSizeKey)) return [3 /*break*/, 6];
335 return [4 /*yield*/, this._isExpired(key)];
336 case 3:
337 if (!_a.sent()) return [3 /*break*/, 5];
338 return [4 /*yield*/, this._removeItem(key)];
339 case 4:
340 _a.sent();
341 return [3 /*break*/, 6];
342 case 5:
343 keys.push(key);
344 _a.label = 6;
345 case 6:
346 i += 1;
347 return [3 /*break*/, 2];
348 case 7: return [2 /*return*/, keys];
349 }
350 });
351 });
352 };
353 /**
354 * get all the items we have, sort them by their priority,
355 * if priority is same, sort them by their last visited time
356 * pop out items from the low priority (5 is the lowest)
357 * @private
358 * @param keys - all the keys in this cache
359 * @param sizeToPop - the total size of the items which needed to be poped out
360 */
361 AsyncStorageCache.prototype._popOutItems = function (keys, sizeToPop) {
362 return __awaiter(this, void 0, void 0, function () {
363 var items, remainedSize, i, val, item, i;
364 return __generator(this, function (_a) {
365 switch (_a.label) {
366 case 0:
367 items = [];
368 remainedSize = sizeToPop;
369 i = 0;
370 _a.label = 1;
371 case 1:
372 if (!(i < keys.length)) return [3 /*break*/, 4];
373 return [4 /*yield*/, react_native_1.AsyncStorage.getItem(keys[i])];
374 case 2:
375 val = _a.sent();
376 if (val != null) {
377 item = JSON.parse(val);
378 items.push(item);
379 }
380 _a.label = 3;
381 case 3:
382 i += 1;
383 return [3 /*break*/, 1];
384 case 4:
385 // first compare priority
386 // then compare visited time
387 items.sort(function (a, b) {
388 if (a.priority > b.priority) {
389 return -1;
390 }
391 else if (a.priority < b.priority) {
392 return 1;
393 }
394 else {
395 if (a.visitedTime < b.visitedTime) {
396 return -1;
397 }
398 else
399 return 1;
400 }
401 });
402 i = 0;
403 _a.label = 5;
404 case 5:
405 if (!(i < items.length)) return [3 /*break*/, 8];
406 // pop out items until we have enough room for new item
407 return [4 /*yield*/, this._removeItem(items[i].key, items[i].byteSize)];
408 case 6:
409 // pop out items until we have enough room for new item
410 _a.sent();
411 remainedSize -= items[i].byteSize;
412 if (remainedSize <= 0) {
413 return [2 /*return*/];
414 }
415 _a.label = 7;
416 case 7:
417 i += 1;
418 return [3 /*break*/, 5];
419 case 8: return [2 /*return*/];
420 }
421 });
422 });
423 };
424 /**
425 * Set item into cache. You can put number, string, boolean or object.
426 * The cache will first check whether has the same key.
427 * If it has, it will delete the old item and then put the new item in
428 * The cache will pop out items if it is full
429 * You can specify the cache item options. The cache will abort and output a warning:
430 * If the key is invalid
431 * If the size of the item exceeds itemMaxSize.
432 * If the value is undefined
433 * If incorrect cache item configuration
434 * If error happened with browser storage
435 *
436 * @param {String} key - the key of the item
437 * @param {Object} value - the value of the item
438 * @param {Object} [options] - optional, the specified meta-data
439 * @return {Prmoise}
440 */
441 AsyncStorageCache.prototype.setItem = function (key, value, options) {
442 return __awaiter(this, void 0, void 0, function () {
443 var prefixedKey, cacheItemOptions, item, val, validKeys, sizeToPop, e_1;
444 return __generator(this, function (_a) {
445 switch (_a.label) {
446 case 0:
447 logger.debug("Set item: key is " + key + ", value is " + value + " with options: " + options);
448 prefixedKey = this.config.keyPrefix + key;
449 // invalid keys
450 if (prefixedKey === this.config.keyPrefix ||
451 prefixedKey === this.cacheCurSizeKey) {
452 logger.warn("Invalid key: should not be empty or 'CurSize'");
453 return [2 /*return*/];
454 }
455 if (typeof value === 'undefined') {
456 logger.warn("The value of item should not be undefined!");
457 return [2 /*return*/];
458 }
459 cacheItemOptions = {
460 priority: options && options.priority !== undefined
461 ? options.priority
462 : this.config.defaultPriority,
463 expires: options && options.expires !== undefined
464 ? options.expires
465 : this.config.defaultTTL + Utils_1.getCurrTime(),
466 };
467 if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {
468 logger.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");
469 return [2 /*return*/];
470 }
471 item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);
472 // check wether this item is too big;
473 if (item.byteSize > this.config.itemMaxSize) {
474 logger.warn("Item with key: " + key + " you are trying to put into is too big!");
475 return [2 /*return*/];
476 }
477 _a.label = 1;
478 case 1:
479 _a.trys.push([1, 12, , 13]);
480 return [4 /*yield*/, react_native_1.AsyncStorage.getItem(prefixedKey)];
481 case 2:
482 val = _a.sent();
483 if (!val) return [3 /*break*/, 4];
484 return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(val).byteSize)];
485 case 3:
486 _a.sent();
487 _a.label = 4;
488 case 4: return [4 /*yield*/, this._isCacheFull(item.byteSize)];
489 case 5:
490 if (!_a.sent()) return [3 /*break*/, 10];
491 return [4 /*yield*/, this._findValidKeys()];
492 case 6:
493 validKeys = _a.sent();
494 return [4 /*yield*/, this._isCacheFull(item.byteSize)];
495 case 7:
496 if (!_a.sent()) return [3 /*break*/, 10];
497 return [4 /*yield*/, this._sizeToPop(item.byteSize)];
498 case 8:
499 sizeToPop = _a.sent();
500 return [4 /*yield*/, this._popOutItems(validKeys, sizeToPop)];
501 case 9:
502 _a.sent();
503 _a.label = 10;
504 case 10:
505 // put item in the cache
506 return [4 /*yield*/, this._setItem(prefixedKey, item)];
507 case 11:
508 // put item in the cache
509 _a.sent();
510 return [3 /*break*/, 13];
511 case 12:
512 e_1 = _a.sent();
513 logger.warn("setItem failed! " + e_1);
514 return [3 /*break*/, 13];
515 case 13: return [2 /*return*/];
516 }
517 });
518 });
519 };
520 /**
521 * Get item from cache. It will return null if item doesn’t exist or it has been expired.
522 * If you specified callback function in the options,
523 * then the function will be executed if no such item in the cache
524 * and finally put the return value into cache.
525 * Please make sure the callback function will return the value you want to put into the cache.
526 * The cache will abort output a warning:
527 * If the key is invalid
528 * If error happened with AsyncStorage
529 *
530 * @param {String} key - the key of the item
531 * @param {Object} [options] - the options of callback function
532 * @return {Promise} - return a promise resolves to be the value of the item
533 */
534 AsyncStorageCache.prototype.getItem = function (key, options) {
535 return __awaiter(this, void 0, void 0, function () {
536 var ret, prefixedKey, item, val, e_2;
537 return __generator(this, function (_a) {
538 switch (_a.label) {
539 case 0:
540 logger.debug("Get item: key is " + key + " with options " + options);
541 ret = null;
542 prefixedKey = this.config.keyPrefix + key;
543 if (prefixedKey === this.config.keyPrefix ||
544 prefixedKey === this.cacheCurSizeKey) {
545 logger.warn("Invalid key: should not be empty or 'CurSize'");
546 return [2 /*return*/, null];
547 }
548 _a.label = 1;
549 case 1:
550 _a.trys.push([1, 8, , 9]);
551 return [4 /*yield*/, react_native_1.AsyncStorage.getItem(prefixedKey)];
552 case 2:
553 ret = _a.sent();
554 if (!(ret != null)) return [3 /*break*/, 7];
555 return [4 /*yield*/, this._isExpired(prefixedKey)];
556 case 3:
557 if (!_a.sent()) return [3 /*break*/, 5];
558 // if expired, remove that item and return null
559 return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(ret).byteSize)];
560 case 4:
561 // if expired, remove that item and return null
562 _a.sent();
563 return [3 /*break*/, 7];
564 case 5:
565 item = JSON.parse(ret);
566 return [4 /*yield*/, this._refreshItem(item, prefixedKey)];
567 case 6:
568 item = _a.sent();
569 return [2 /*return*/, item.data];
570 case 7:
571 if (options && options.callback !== undefined) {
572 val = options.callback();
573 if (val !== null) {
574 this.setItem(key, val, options);
575 }
576 return [2 /*return*/, val];
577 }
578 return [2 /*return*/, null];
579 case 8:
580 e_2 = _a.sent();
581 logger.warn("getItem failed! " + e_2);
582 return [2 /*return*/, null];
583 case 9: return [2 /*return*/];
584 }
585 });
586 });
587 };
588 /**
589 * remove item from the cache
590 * The cache will abort output a warning:
591 * If error happened with AsyncStorage
592 * @param {String} key - the key of the item
593 * @return {Promise}
594 */
595 AsyncStorageCache.prototype.removeItem = function (key) {
596 return __awaiter(this, void 0, void 0, function () {
597 var prefixedKey, val, e_3;
598 return __generator(this, function (_a) {
599 switch (_a.label) {
600 case 0:
601 logger.debug("Remove item: key is " + key);
602 prefixedKey = this.config.keyPrefix + key;
603 if (prefixedKey === this.config.keyPrefix ||
604 prefixedKey === this.cacheCurSizeKey) {
605 return [2 /*return*/];
606 }
607 _a.label = 1;
608 case 1:
609 _a.trys.push([1, 5, , 6]);
610 return [4 /*yield*/, react_native_1.AsyncStorage.getItem(prefixedKey)];
611 case 2:
612 val = _a.sent();
613 if (!val) return [3 /*break*/, 4];
614 return [4 /*yield*/, this._removeItem(prefixedKey, JSON.parse(val).byteSize)];
615 case 3:
616 _a.sent();
617 _a.label = 4;
618 case 4: return [3 /*break*/, 6];
619 case 5:
620 e_3 = _a.sent();
621 logger.warn("removeItem failed! " + e_3);
622 return [3 /*break*/, 6];
623 case 6: return [2 /*return*/];
624 }
625 });
626 });
627 };
628 /**
629 * clear the entire cache
630 * The cache will abort output a warning:
631 * If error happened with AsyncStorage
632 * @return {Promise}
633 */
634 AsyncStorageCache.prototype.clear = function () {
635 return __awaiter(this, void 0, void 0, function () {
636 var keys, keysToRemove, i, i, e_4;
637 return __generator(this, function (_a) {
638 switch (_a.label) {
639 case 0:
640 logger.debug("Clear Cache");
641 _a.label = 1;
642 case 1:
643 _a.trys.push([1, 7, , 8]);
644 return [4 /*yield*/, react_native_1.AsyncStorage.getAllKeys()];
645 case 2:
646 keys = _a.sent();
647 keysToRemove = [];
648 for (i = 0; i < keys.length; i += 1) {
649 if (keys[i].indexOf(this.config.keyPrefix) === 0) {
650 keysToRemove.push(keys[i]);
651 }
652 }
653 i = 0;
654 _a.label = 3;
655 case 3:
656 if (!(i < keysToRemove.length)) return [3 /*break*/, 6];
657 return [4 /*yield*/, react_native_1.AsyncStorage.removeItem(keysToRemove[i])];
658 case 4:
659 _a.sent();
660 _a.label = 5;
661 case 5:
662 i += 1;
663 return [3 /*break*/, 3];
664 case 6: return [3 /*break*/, 8];
665 case 7:
666 e_4 = _a.sent();
667 logger.warn("clear failed! " + e_4);
668 return [3 /*break*/, 8];
669 case 8: return [2 /*return*/];
670 }
671 });
672 });
673 };
674 /**
675 * return the current size of the cache
676 * @return {Promise}
677 */
678 AsyncStorageCache.prototype.getCacheCurSize = function () {
679 return __awaiter(this, void 0, void 0, function () {
680 var ret;
681 return __generator(this, function (_a) {
682 switch (_a.label) {
683 case 0: return [4 /*yield*/, react_native_1.AsyncStorage.getItem(this.cacheCurSizeKey)];
684 case 1:
685 ret = _a.sent();
686 if (!!ret) return [3 /*break*/, 3];
687 return [4 /*yield*/, react_native_1.AsyncStorage.setItem(this.cacheCurSizeKey, '0')];
688 case 2:
689 _a.sent();
690 ret = '0';
691 _a.label = 3;
692 case 3: return [2 /*return*/, Number(ret)];
693 }
694 });
695 });
696 };
697 /**
698 * Return all the keys in the cache.
699 * Will return an empty array if error happend.
700 * @return {Promise}
701 */
702 AsyncStorageCache.prototype.getAllKeys = function () {
703 return __awaiter(this, void 0, void 0, function () {
704 var keys, retKeys, i, e_5;
705 return __generator(this, function (_a) {
706 switch (_a.label) {
707 case 0:
708 _a.trys.push([0, 2, , 3]);
709 return [4 /*yield*/, react_native_1.AsyncStorage.getAllKeys()];
710 case 1:
711 keys = _a.sent();
712 retKeys = [];
713 for (i = 0; i < keys.length; i += 1) {
714 if (keys[i].indexOf(this.config.keyPrefix) === 0 &&
715 keys[i] !== this.cacheCurSizeKey) {
716 retKeys.push(keys[i].substring(this.config.keyPrefix.length));
717 }
718 }
719 return [2 /*return*/, retKeys];
720 case 2:
721 e_5 = _a.sent();
722 logger.warn("getALlkeys failed! " + e_5);
723 return [2 /*return*/, []];
724 case 3: return [2 /*return*/];
725 }
726 });
727 });
728 };
729 /**
730 * Return a new instance of cache with customized configuration.
731 * @param {Object} config - the customized configuration
732 * @return {Object} - the new instance of Cache
733 */
734 AsyncStorageCache.prototype.createInstance = function (config) {
735 if (config.keyPrefix === Utils_1.defaultConfig.keyPrefix) {
736 logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');
737 config.keyPrefix = Utils_1.getCurrTime.toString();
738 }
739 return new AsyncStorageCache(config);
740 };
741 return AsyncStorageCache;
742}(StorageCache_1.StorageCache));
743exports.AsyncStorageCache = AsyncStorageCache;
744var instance = new AsyncStorageCache();
745exports.Cache = instance;
746exports.default = instance;
747//# sourceMappingURL=AsyncStorageCache.js.map
\No newline at end of file