Created
January 18, 2023 09:54
-
-
Save rony-arnac/29bb877db35591b6ed98b0afe9f1d77d to your computer and use it in GitHub Desktop.
better storage management that handles concurrent access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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