Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Last active November 1, 2023 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonbosa/15969d29251a7c4b3f24de08778fa860 to your computer and use it in GitHub Desktop.
Save andersonbosa/15969d29251a7c4b3f24de08778fa860 to your computer and use it in GitHub Desktop.
type CustomStorage = {
data: { [key: string]: string }
setItem: (key: string, value: string) => void
getItem: (key: string) => string | null
}
type StorageType = 'localStorage' | 'customStorage'
class StorageManager {
storage: Storage | CustomStorage
key: string
storageType: StorageType
constructor(key: string, storageType: StorageType = 'localStorage', customStorage?: CustomStorage) {
this.key = key
this.storageType = storageType
if (this.storageType === 'customStorage' && customStorage) {
this.storage = customStorage
} else {
this.storage = localStorage
}
const storedData = this.storage.getItem(this.key)
if (!storedData) {
this.storage.setItem(this.key, JSON.stringify({}))
}
}
getData (): { [key: string]: any } {
const data = this.storage.getItem(this.key)
return data ? JSON.parse(data) : {}
}
setData (data: { [key: string]: any }) {
this.storage.setItem(this.key, JSON.stringify(data))
}
addItem (key: string, value: any) {
const data = this.getData()
data[key] = value
this.setData(data)
}
removeItem (key: string) {
const data = this.getData()
delete data[key]
this.setData(data)
}
updateItem (key: string, value: any) {
const data = this.getData()
if (data.hasOwnProperty(key)) {
data[key] = value
this.setData(data)
} else {
throw new Error(`Key ${key} does not exist in storage.`)
}
}
}
// Usage with localStorage
const storageManagerLocalStorage = new StorageManager('MYCUSTOMSTORAGE', 'localStorage')
storageManagerLocalStorage.addItem('foo', 'boo')
console.log(storageManagerLocalStorage.getData())
// Usage with customStorage
const customStorage: CustomStorage = {
data: {},
setItem (key: string, value: string) {
this.data[key] = value
},
getItem (key: string) {
return this.data[key] || null
}
}
const storageManagerCustom = new StorageManager('MYLOCALSTORAGE', 'customStorage', customStorage)
storageManagerCustom.addItem('foo', 'boo')
console.log(storageManagerCustom.getData())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment