Created
December 25, 2022 23:14
-
-
Save guiseek/1ff9e4fbb535f256ab541bcdd0f4d6e0 to your computer and use it in GitHub Desktop.
Storage
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
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