Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active March 29, 2019 12:28
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 amatiasq/540e50c21b58c3aab66ce1c70dc9197a to your computer and use it in GitHub Desktop.
Save amatiasq/540e50c21b58c3aab66ce1c70dc9197a to your computer and use it in GitHub Desktop.
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);
}
}
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