Skip to content
Closed
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
43 changes: 42 additions & 1 deletion lib/storage/providers/LocalForage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,43 @@ localforage.config({
name: 'OnyxDB'
});

class SynchronousWriteQueue {
constructor() {
this.isWriting = false;
this.queue = [];
}

push(item) {
this.queue.push(item);
this.process();
}

process() {
if (this.isWriting) {
return;
}

this.isWriting = true;
const next = this.queue.shift();
if (!next) {
this.isWriting = false;
return;
}

const {
key, value, resolve, reject,
} = next;
localforage.setItem(key, value)
.then(resolve)
.catch(reject)
.finally(() => {
this.isWriting = false;
this.process();
});
}
}

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

export default provider;