@aws-amplify/core
Version:
Core category of aws-amplify
104 lines (101 loc) • 3.64 kB
JavaScript
import { loadAsyncStorage } from '@aws-amplify/react-native';
import { DATABASE_NAME } from './constants.mjs';
import { getAddItemBytesSize } from './getAddItemBytesSize.mjs';
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
const keyPrefix = `@${DATABASE_NAME}`;
const createQueuedStorage = () => {
let currentBytesSize = 0;
let error;
const openDBPromise = new Promise((resolve, _reject) => {
try {
const asyncStorage = loadAsyncStorage();
getQueuedItemKeys(asyncStorage)
.then(keys => getQueuedItems(asyncStorage, keys))
.then(items => {
for (const item of items) {
currentBytesSize += item.bytesSize;
}
return undefined;
})
.then(__ => {
resolve(asyncStorage);
});
}
catch (err) {
error = err;
resolve(undefined);
}
});
const getAsyncStorage = async () => {
const as = await openDBPromise;
if (!as) {
throw error;
}
return as;
};
const _peek = async (n) => {
const as = await getAsyncStorage();
const queuedItemKeys = await getQueuedItemKeys(as, true);
const keysToGetValues = queuedItemKeys.slice(0, n);
return getQueuedItems(as, keysToGetValues);
};
return {
async add(item, { dequeueBeforeEnqueue } = { dequeueBeforeEnqueue: false }) {
if (dequeueBeforeEnqueue) {
const itemsToDelete = await this.peek(1);
await this.delete(itemsToDelete);
}
const as = await getAsyncStorage();
const itemBytesSize = getAddItemBytesSize(item);
const key = `${keyPrefix}_${Date.now()}`;
const queuedItem = {
...item,
bytesSize: itemBytesSize,
key,
};
await as.setItem(key, JSON.stringify(queuedItem));
currentBytesSize += itemBytesSize;
},
async peek(n) {
return _peek(n);
},
async peekAll() {
return _peek();
},
async delete(items) {
const as = await getAsyncStorage();
const keysToDelete = items
.map(item => item.key)
.filter((id) => id !== undefined);
await as.multiRemove(keysToDelete);
for (const item of items) {
currentBytesSize -= item.bytesSize;
}
},
async clear() {
const as = await getAsyncStorage();
const keysToDelete = await getQueuedItemKeys(as);
await as.multiRemove(keysToDelete);
currentBytesSize = 0;
},
isFull(maxBytesSizeInMiB) {
return currentBytesSize >= maxBytesSizeInMiB * 1024 * 1024;
},
};
};
const getQueuedItemKeys = async (as, sortKeys = false) => {
const keys = (await as.getAllKeys()).filter(key => key.startsWith(keyPrefix));
return sortKeys
? keys.sort((a, b) => {
const timestampA = a.split('_').pop();
const timestampB = b.split('_').pop();
return parseInt(timestampA) - parseInt(timestampB);
})
: keys;
};
const getQueuedItems = async (as, keys) => (await as.multiGet(keys))
.filter((item) => item[1] !== null)
.map(([_, value]) => JSON.parse(value));
export { createQueuedStorage, keyPrefix };
//# sourceMappingURL=createQueuedStorage.native.mjs.map