Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created December 25, 2022 23:14
Show Gist options
  • Save guiseek/1ff9e4fbb535f256ab541bcdd0f4d6e0 to your computer and use it in GitHub Desktop.
Save guiseek/1ff9e4fbb535f256ab541bcdd0f4d6e0 to your computer and use it in GitHub Desktop.
Storage
export class FrontendStorageService<T extends StorageMap> {
private _storage: Storage
constructor(storage: Storage) {
this._storage = storage
}
get<K extends keyof T>(key: K) {
const data = this._storage.getItem(String(key))
if (data) {
try {
return JSON.parse(data)
} catch {
return data
}
}
}
set<K extends keyof T>(key: K, value: T[K]) {
if (value) {
const data = typeof value !== 'string' ? JSON.stringify(value) : value
this._storage.setItem(String(key), data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment