Last active
December 26, 2024 18:05
-
-
Save salmin89/17be9b2b738c01260c2013b1116a37d4 to your computer and use it in GitHub Desktop.
a wrapper for chrome.storage that allows for partial updates
This file contains hidden or 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
(async () => { | |
await StorageLocal.set({ user1: { name: "Bob", age: 20 } }); | |
await StorageLocal.get("user1").then((user) => { | |
console.log("get after set", user); | |
}); | |
await StorageLocal.patch({ user1: { age: 21 } }); | |
await StorageLocal.get("user1").then((user) => { | |
console.log("get after patch", user); | |
}); | |
await StorageLocal.put({ user1: { name: "Updated" } }); | |
await StorageLocal.get("user1").then((user) => { | |
console.log("get after put", user); | |
}); | |
})(); |
This file contains hidden or 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
type StorageKinds = "local" | "sync" | "managed" | "session"; | |
class StorageAPI { | |
kind: StorageKinds; | |
cache: Promise<{ [key: string]: any }>; | |
constructor(kind: StorageKinds) { | |
this.kind = kind; | |
this.cache = chrome.storage[kind].get(null); | |
} | |
async get(key: string): Promise<any> { | |
const storage = await this.cache; | |
if (storage) return storage[key]; | |
console.warn("no cache"); | |
return chrome.storage[this.kind].get(key); | |
} | |
async patch(partial: Record<string, any>): Promise<any> { | |
const key = Object.keys(partial)[0]; | |
const storage = await this.cache; | |
const current = storage[key]; | |
// mutating the cached copy | |
storage[key] = { ...current, ...partial[key] }; | |
return chrome.storage[this.kind].set({ [key]: storage[key] }); | |
} | |
async put(object: Record<string, any>): Promise<any> { | |
const key = Object.keys(object)[0]; | |
const storage = await this.cache; | |
// updating the cached copy | |
storage[key] = object[key]; | |
return chrome.storage[this.kind].set({ [key]: storage[key] }); | |
} | |
async set(partial: Record<string, any>): Promise<any> { | |
await this.cache; | |
return chrome.storage[this.kind].set(partial); | |
} | |
} | |
export const StorageLocal = new StorageAPI("local"); | |
// export const StorageSync = new StorageAPI("sync"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment