DRY chromeLocal and chromeSync

This commit is contained in:
tophf 2017-12-10 10:02:43 +03:00
parent b2b82f8310
commit 5d54ce3464

View File

@ -30,47 +30,37 @@ var cachedStyles = {
}; };
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var chromeLocal = { var [chromeLocal, chromeSync] = [
chrome.storage.local,
chrome.storage.sync,
].map(storage => {
const wrapper = {
get(options) { get(options) {
return new Promise(resolve => { return new Promise(resolve => {
chrome.storage.local.get(options, data => resolve(data)); storage.get(options, data => resolve(data));
}); });
}, },
set(data) { set(data) {
return new Promise(resolve => { return new Promise(resolve => {
chrome.storage.local.set(data, () => resolve(data)); storage.set(data, () => resolve(data));
}); });
}, },
remove(keyOrKeys) { remove(keyOrKeys) {
return new Promise(resolve => { return new Promise(resolve => {
chrome.storage.local.remove(keyOrKeys, resolve); storage.remove(keyOrKeys, resolve);
}); });
}, },
getValue(key) { getValue(key) {
return chromeLocal.get(key).then(data => data[key]); return wrapper.get(key).then(data => data[key]);
}, },
setValue(key, value) { setValue(key, value) {
return chromeLocal.set({[key]: value}); return wrapper.set({[key]: value});
},
};
// eslint-disable-next-line no-var
var chromeSync = {
get(options) {
return new Promise(resolve => {
chrome.storage.sync.get(options, resolve);
});
},
set(data) {
return new Promise(resolve => {
chrome.storage.sync.set(data, () => resolve(data));
});
}, },
getLZValue(key) { getLZValue(key) {
return chromeSync.getLZValues([key]).then(data => data[key]); return wrapper.getLZValues([key]).then(data => data[key]);
}, },
getLZValues(keys) { getLZValues(keys) {
return chromeSync.get(keys).then((data = {}) => { return wrapper.get(keys).then((data = {}) => {
for (const key of keys) { for (const key of keys) {
const value = data[key]; const value = data[key];
data[key] = value && tryJSONparse(LZString.decompressFromUTF16(value)); data[key] = value && tryJSONparse(LZString.decompressFromUTF16(value));
@ -79,9 +69,11 @@ var chromeSync = {
}); });
}, },
setLZValue(key, value) { setLZValue(key, value) {
return chromeSync.set({[key]: LZString.compressToUTF16(JSON.stringify(value))}); return wrapper.set({[key]: LZString.compressToUTF16(JSON.stringify(value))});
} }
}; };
return wrapper;
});
// eslint-disable-next-line no-var // eslint-disable-next-line no-var
var dbExec = dbExecIndexedDB; var dbExec = dbExecIndexedDB;