Last active
March 29, 2019 12:28
-
-
Save amatiasq/540e50c21b58c3aab66ce1c70dc9197a to your computer and use it in GitHub Desktop.
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
const DEFAULT_VERSION = 0; | |
export class ClientStorage { | |
constructor(key, { | |
isSessionOnly = false, | |
version = DEFAULT_VERSION, | |
} = {}) { | |
this.key = key; | |
this.version = version; | |
this.storage = isSessionOnly ? sessionStorage : localStorage; | |
} | |
save(json) { | |
const data = Object.assign({}, json, { version: this.version }); | |
this.storage.setItem(this.key, JSON.stringify(data)); | |
} | |
load() { | |
const json = this.storage.getItem(this.key); | |
if (!json) return null; | |
const data = JSON.parse(json); | |
if (data.version !== this.version) { | |
this.reset(); | |
return null; | |
} | |
delete data.version; | |
return data; | |
} | |
reset() { | |
this.storage.removeItem(this.key); | |
} | |
} |
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
const DEFAULT_VERSION = 0; | |
interface IStorageOptions { | |
version?: number; | |
isSessionOnly?: boolean; | |
} | |
export class ClientStorage<T = any> { | |
readonly version: number; | |
private readonly storage: Storage; | |
constructor( | |
private readonly key: string, | |
{ isSessionOnly = false, version = DEFAULT_VERSION }: IStorageOptions = {}, | |
) { | |
this.version = version; | |
this.storage = isSessionOnly ? sessionStorage : localStorage; | |
} | |
save(json: T) { | |
const data = { ...json, version: this.version }; | |
this.storage.setItem(this.key, JSON.stringify(data)); | |
} | |
load(): T { | |
const json = this.storage.getItem(this.key); | |
if (!json) return null; | |
const data = JSON.parse(json); | |
if (data.version !== this.version) { | |
this.reset(); | |
return null; | |
} | |
delete data.version; | |
return data; | |
} | |
reset() { | |
this.storage.removeItem(this.key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment