Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add write queue to localForage storage provider #121

Merged
merged 2 commits into from
Mar 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion lib/storage/providers/LocalForage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,33 @@ localforage.config({
name: 'OnyxDB'
});

const writeQueue = [];
let isQueueProcessing = false;

/**
* Writing very quickly to IndexedDB causes performance issues and can lock up the page and lead to jank.
* So, we are slowing this process down by waiting until one write is complete before moving on
* to the next.
*/
function processNextWrite() {
if (isQueueProcessing || writeQueue.length === 0) {
return;
}

isQueueProcessing = true;

const {
key, value, resolve, reject,
} = writeQueue.shift();
localforage.setItem(key, value)
.then(resolve)
.catch(reject)
.finally(() => {
isQueueProcessing = false;
processNextWrite();
});
}

const provider = {
/**
* Get multiple key-value pairs for the give array of keys in a batch
Expand Down Expand Up @@ -90,7 +117,14 @@ const provider = {
* @param {*} value
* @return {Promise<void>}
*/
setItem: localforage.setItem,
setItem: (key, value) => (
new Promise((resolve, reject) => {
writeQueue.push({
key, value, resolve, reject,
});
processNextWrite();
})
),
};

export default provider;
14 changes: 9 additions & 5 deletions tests/unit/storage/providers/LocalForageProviderTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,21 @@ describe('storage/providers/LocalForage', () => {

// For some reason fake timers cause promises to hang
beforeAll(() => jest.useRealTimers());
beforeEach(() => jest.resetAllMocks());
beforeEach(() => {
jest.resetAllMocks();
localforage.setItem = jest.fn(() => Promise.resolve());
});

it('multiSet', () => {
// Given multiple pairs to be saved in storage
const pairs = SAMPLE_ITEMS.slice();

// When they are saved
StorageProvider.multiSet(pairs);

// We expect a call to localForage.setItem for each pair
_.each(pairs, ([key, value]) => expect(localforage.setItem).toHaveBeenCalledWith(key, value));
return StorageProvider.multiSet(pairs)
.then(() => {
// We expect a call to localForage.setItem for each pair
_.each(pairs, ([key, value]) => expect(localforage.setItem).toHaveBeenCalledWith(key, value));
});
});

it('multiGet', () => {
Expand Down