stylus/js/storage-util.js

62 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-10-10 15:05:20 +00:00
/* global loadScript tryJSONparse API */
/* exported chromeLocal chromeSync */
2018-01-01 17:02:49 +00:00
'use strict';
2018-10-10 15:05:20 +00:00
const [chromeLocal, chromeSync] = (() => {
return [
createWrapper('local'),
createWrapper('sync'),
];
2018-01-01 17:02:49 +00:00
function createWrapper(name) {
const storage = chrome.storage[name];
const wrapper = {
get: data => new Promise(resolve => storage.get(data, resolve)),
set: data => new Promise(resolve => storage.set(data, () => resolve(data))),
remove: data => new Promise(resolve => storage.remove(data, resolve)),
2018-01-01 17:02:49 +00:00
2018-05-09 15:33:13 +00:00
/**
* @param {String} key
* @param {Any} [defaultValue]
* @returns {Promise<any>}
*/
getValue: (key, defaultValue) =>
wrapper.get(
defaultValue !== undefined ?
{[key]: defaultValue} :
key
).then(data => data[key]),
setValue: (key, value) => wrapper.set({[key]: value}),
getLZValue: key => wrapper.getLZValues([key]).then(data => data[key]),
getLZValues: keys =>
Promise.all([
wrapper.get(keys),
loadLZStringScript(),
]).then(([data = {}, LZString]) => {
for (const key of keys) {
const value = data[key];
data[key] = value && tryJSONparse(LZString.decompressFromUTF16(value));
}
return data;
}),
setLZValue: (key, value) =>
loadLZStringScript().then(LZString =>
wrapper.set({
[key]: LZString.compressToUTF16(JSON.stringify(value)),
})),
loadLZStringScript,
};
return wrapper;
2018-01-01 17:02:49 +00:00
}
function loadLZStringScript() {
return window.LZString ?
Promise.resolve(window.LZString) :
2018-07-21 17:58:54 +00:00
loadScript('/vendor/lz-string-unsafe/lz-string-unsafe.min.js').then(() =>
(window.LZString = window.LZString || window.LZStringUnsafe));
2018-01-01 17:02:49 +00:00
}
})();