Skip to content

Instantly share code, notes, and snippets.

@rony-arnac
Created January 18, 2023 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rony-arnac/29bb877db35591b6ed98b0afe9f1d77d to your computer and use it in GitHub Desktop.
Save rony-arnac/29bb877db35591b6ed98b0afe9f1d77d to your computer and use it in GitHub Desktop.
better storage management that handles concurrent access
const globalKey = 'FORDEFI_data';
const divider = '--';
async function storeComplexData (complexData: Record<string, string[]>) {
// Flatten the complex object to avoid it being overwritten
for (const [itemKey, itemValue] of Object.entries(complexData)) {
const newKey = `${globalKey}${divider}${itemKey}`;
await chrome.storage.local.set({[newKey]: itemValue});
}
}
// Get the whole complex structure
async function getComplexData () {
const storageItems = await chrome.storage.local.get(null);
const itemKeys = Object.keys(storageItems).filter(
key => key.startsWith(globalKey)
);
const complexData: Record<string, string[]> = {};
for (const key of itemKeys) {
const [_, complexDataItemKey] = key.split(divider);
complexData[complexDataItemKey] = storageItems[key];
}
return complexData;
}
// Get the value of a specific key in our complex structure
async function getComplexDataItem (complexDataItemKey: string) {
const storageItems = await chrome.storage.local.get(null);
const newKey = `${globalKey}${divider}${complexDataItemKey}`;
const itemKeys = Object.keys(storageItems).filter(
key => key === newKey
);
if (itemKeys.length === 0) {
return undefined;
}
return storageItems[itemKeys[0]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment