Created
March 17, 2020 15:44
-
-
Save neevai/f3ed458577891c61e1c5c175e3d1f893 to your computer and use it in GitHub Desktop.
An Amplify.Storage class for Chrome extensions
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
/* global chrome */ | |
const MEMORY_KEY_PREFIX = '@BackgroundStorage:'; | |
let dataMemory = {}; | |
export default class BackgroundStorage { | |
static syncPromise = null; | |
static setItem(key, value) { | |
chrome.runtime.sendMessage({action: 'store', subAction: 'setItem', key: MEMORY_KEY_PREFIX + key, value}); | |
dataMemory[key] = value; | |
return dataMemory[key]; | |
}; | |
static getItem(key) { | |
return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; | |
}; | |
static removeItem(key) { | |
chrome.runtime.sendMessage({action: 'store', subAction: 'removeItem', key: MEMORY_KEY_PREFIX + key}); | |
return delete dataMemory[key]; | |
} | |
static clear() { | |
chrome.runtime.sendMessage({action: 'store', subAction: 'clear'}); | |
dataMemory = {}; | |
return dataMemory; | |
} | |
static sync() { | |
if (!BackgroundStorage.syncPromise) { | |
BackgroundStorage.syncPromise = new Promise((res, rej) => { | |
chrome.runtime.sendMessage({action: 'store', subAction: 'getAllKeys'}, messageResponse => { | |
const [response, error] = messageResponse; | |
if (error) rej(error); | |
const memoryKeys = response.filter((key) => key.startsWith(MEMORY_KEY_PREFIX)); | |
chrome.runtime.sendMessage({action: 'store', subAction: 'multiGet', keys: memoryKeys}, messageResponse => { | |
const [response, error] = messageResponse; | |
if (error) rej(error); | |
Object.keys(response).forEach(key => { | |
const memoryKey = key.replace(MEMORY_KEY_PREFIX, ''); | |
dataMemory[memoryKey] = response[key]; | |
}); | |
res(); | |
}); | |
}); | |
}); | |
} | |
return BackgroundStorage.syncPromise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment