Skip to content

Instantly share code, notes, and snippets.

@ken-miyashita
Created January 10, 2022 01:39
Show Gist options
  • Select an option

  • Save ken-miyashita/3ed62127c8a224e3f9a136a2ee028061 to your computer and use it in GitHub Desktop.

Select an option

Save ken-miyashita/3ed62127c8a224e3f9a136a2ee028061 to your computer and use it in GitHub Desktop.
Simplified SharedAuthStorage.ts for blog
const CHROME_STORAGE_KEY_PREFIX = 'AmplifyStorage-';
/**
* Enumerate all relevant key-value items in chrome.storage.local.
* @param operator - operator to apply on items
*/
function enumerateItems(operator) {
chrome.storage.local.get(null, (items) => {
const chromeStorageKeys = Object.keys(items).filter((key) => key.startsWith(CHROME_STORAGE_KEY_PREFIX));
chrome.storage.local.get(chromeStorageKeys, (items => {
// items is an object which has key-value.
// Each key has a prefix, and you need to remove it if you want to access on-memory cache.
operator(items);
}));
});
}
export default class SharedAuthStorage {
static syncPromise: Promise<void> | null = null;
static cache = new Map();
static setItem(key:string, value:string) {
chrome.storage.local.set({[CHROME_STORAGE_KEY_PREFIX + key]: value});
SharedAuthStorage.cache.set(key, value);
}
static getItem(key:string) {
let value = null;
if (SharedAuthStorage.cache.has(key)) {
value = SharedAuthStorage.cache.get(key);
}
return value;
}
static removeItem(key: string) {
chrome.storage.local.remove(CHROME_STORAGE_KEY_PREFIX + key);
SharedAuthStorage.cache.delete(key);
}
static sync() {
if (!SharedAuthStorage.syncPromise) {
SharedAuthStorage.syncPromise = new Promise<void>((res) => {
enumerateItems(items => {
for (const [chromeStorageKey, value] of Object.entries(items)) {
const key = chromeStorageKey.replace(CHROME_STORAGE_KEY_PREFIX, '');
SharedAuthStorage.cache.set(key, value);
}
res();
});
});
}
return SharedAuthStorage.syncPromise;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment