2020-08-14 12:16:01 +00:00
|
|
|
/* global chromeLocal */
|
2020-02-10 14:56:07 +00:00
|
|
|
/* exported createChromeStorageDB */
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
function createChromeStorageDB() {
|
|
|
|
let INC;
|
|
|
|
|
|
|
|
const PREFIX = 'style-';
|
|
|
|
const METHODS = {
|
|
|
|
// FIXME: we don't use this method at all. Should we remove this?
|
2020-08-14 12:16:01 +00:00
|
|
|
get: id => chromeLocal.getValue(PREFIX + id),
|
|
|
|
put: obj =>
|
|
|
|
// FIXME: should we clone the object?
|
|
|
|
Promise.resolve(!obj.id && prepareInc().then(() => Object.assign(obj, {id: INC++})))
|
|
|
|
.then(() => chromeLocal.setValue(PREFIX + obj.id, obj))
|
|
|
|
.then(() => obj.id),
|
2020-02-10 14:56:07 +00:00
|
|
|
putMany: items => prepareInc()
|
2020-08-14 12:16:01 +00:00
|
|
|
.then(() =>
|
|
|
|
chromeLocal.set(items.reduce((data, item) => {
|
|
|
|
if (!item.id) item.id = INC++;
|
|
|
|
data[PREFIX + item.id] = item;
|
|
|
|
return data;
|
|
|
|
}, {})))
|
2020-02-10 14:56:07 +00:00
|
|
|
.then(() => items.map(i => i.id)),
|
2020-08-14 12:16:01 +00:00
|
|
|
delete: id => chromeLocal.remove(PREFIX + id),
|
|
|
|
getAll: () => chromeLocal.get()
|
2020-02-10 14:56:07 +00:00
|
|
|
.then(result => {
|
|
|
|
const output = [];
|
|
|
|
for (const key in result) {
|
|
|
|
if (key.startsWith(PREFIX) && Number(key.slice(PREFIX.length))) {
|
|
|
|
output.push(result[key]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return output;
|
2020-11-18 11:17:15 +00:00
|
|
|
}),
|
2020-02-10 14:56:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return {exec};
|
|
|
|
|
|
|
|
function exec(method, ...args) {
|
|
|
|
if (METHODS[method]) {
|
|
|
|
return METHODS[method](...args)
|
|
|
|
.then(result => {
|
|
|
|
if (method === 'putMany' && result.map) {
|
|
|
|
return result.map(r => ({target: {result: r}}));
|
|
|
|
}
|
|
|
|
return {target: {result}};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return Promise.reject(new Error(`unknown DB method ${method}`));
|
|
|
|
}
|
|
|
|
|
|
|
|
function prepareInc() {
|
|
|
|
if (INC) return Promise.resolve();
|
2020-08-14 12:16:01 +00:00
|
|
|
return chromeLocal.get().then(result => {
|
2020-02-10 14:56:07 +00:00
|
|
|
INC = 1;
|
|
|
|
for (const key in result) {
|
|
|
|
if (key.startsWith(PREFIX)) {
|
|
|
|
const id = Number(key.slice(PREFIX.length));
|
|
|
|
if (id >= INC) {
|
|
|
|
INC = id + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|