Skip to content

Instantly share code, notes, and snippets.

@raynirola
Created October 28, 2024 06:17
Show Gist options
  • Save raynirola/9a779114f3cbeb13ff836e8776ee40b8 to your computer and use it in GitHub Desktop.
Save raynirola/9a779114f3cbeb13ff836e8776ee40b8 to your computer and use it in GitHub Desktop.
import { Account } from '@/pages/Background/cashback'
const StoreArea = {
local: chrome.storage.local,
sync: chrome.storage.sync,
session: chrome.storage.session,
}
export class Storage {
public area: chrome.storage.StorageArea = StoreArea.local
public scope(type: 'local'): this
public scope(type: 'sync'): this
public scope(type: 'session'): this
public scope(type: 'local' | 'sync' | 'session') {
this.area = StoreArea[type]
return this
}
public async get<T>(key: string | string[]): Promise<T> {
const store = await this.area.get(key)
if (Array.isArray(key)) {
return key.reduce((acc, key) => {
return { ...acc, [key]: store[key] }
}, {}) as T
}
return store[key] as T
}
public async set<T>(key: string, value: T): Promise<void>
public async set<T>(value: { [key: string]: T }): Promise<void>
public async set<T>(key: string | { [key: string]: T }, value?: T) {
if (typeof key === 'string') {
return this.area.set({ [key]: value })
}
return this.area.set(key)
}
public async remove(key: string | string[]) {
if (Array.isArray(key)) {
return this.area.remove(key)
}
return this.area.remove(key)
}
public async clear() {
return this.area.clear()
}
public listen<N, O = any>(key: string, callback: (value: N, oldValue?: O) => void) {
const listener = (changes: { [key: string]: chrome.storage.StorageChange }, areaName: string) => {
const area = this.area === StoreArea.local ? 'local' : this.area === StoreArea.sync ? 'sync' : 'session'
if (area === areaName && changes[key]) {
callback(changes[key].newValue as N, changes[key].oldValue as O)
}
}
chrome.storage.onChanged.addListener(listener)
return () => {
chrome.storage.onChanged.removeListener(listener)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment