Skip to content

Instantly share code, notes, and snippets.

@entrptaher
Last active September 15, 2019 14:16
Show Gist options
  • Save entrptaher/05a32b26d8de78d8f34fecb193f38262 to your computer and use it in GitHub Desktop.
Save entrptaher/05a32b26d8de78d8f34fecb193f38262 to your computer and use it in GitHub Desktop.
/**
* Usage:
* import { storage } from "./tab-storage";
* storage(id).set("something", "foo");
* storage(id).get("something"); // => foo
*/
/**
* Get a storage using the localStorage
* @param {String} dbKey some key to identify main storage
*/
const storage = dbKey => {
const baseId = `_${dbKey}`;
const set = (key, value) => {
localStorage.setItem(baseId, JSON.stringify({ [key]: value }));
};
const get = async sKey => {
try {
const items = localStorage.getItem(baseId);
return JSON.parse(items)[sKey];
} catch (error) {
console.error(error);
return {};
}
};
return { set, get };
};
/**
* Usage:
* import { chromeStorage as storage } from "./tab-storage";
* storage(id).set("something", someData);
* storage(id).get("something"); // => foo
*/
/**
* Get a storage using the chrome.storage.local
* @param {String} dbKey some key to identify main storage
*/
const chromeStorage = dbKey => {
const baseId = `_${dbKey}`;
const getAll = () => {
// https://stackoverflow.com/a/49595052
return new Promise(function(resolve, reject) {
chrome.storage.local.get(baseId, function(items) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
reject(chrome.runtime.lastError.message);
} else {
resolve(items[baseId]);
}
});
});
};
const set = (key, value) => {
const data = { [baseId]: { [key]: value } };
chrome.storage.local.set(data);
};
const get = async sKey => {
try{
const items = await getAll();
return items && items[sKey];
}catch(error){
console.error(error);
return {};
}
};
return { set, get, getAll };
};
module.exports = { storage, chromeStorage };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment