100 lines
2.5 KiB
TypeScript
100 lines
2.5 KiB
TypeScript
|
/**
|
||
|
* Persistent storage, in particular `localStorage`.
|
||
|
*/
|
||
|
export class Storage {
|
||
|
private readonly key: string;
|
||
|
private _cache: { [key: string]: string } | null = null;
|
||
|
|
||
|
|
||
|
/**
|
||
|
* Constructs a new persistent storage item under the given key.
|
||
|
*
|
||
|
* @param key the unique identifier to store the data under
|
||
|
*/
|
||
|
constructor(key: string) {
|
||
|
this.key = key;
|
||
|
}
|
||
|
|
||
|
|
||
|
/**
|
||
|
* Reads the object stored in local storage.
|
||
|
*
|
||
|
* @return the object stored in local storage, or an empty object if there is nothing in the local storage
|
||
|
* @private
|
||
|
*/
|
||
|
private read(): { [key: string]: string } {
|
||
|
if (this._cache === null)
|
||
|
this._cache = JSON.parse(localStorage.getItem(this.key) ?? "{}");
|
||
|
|
||
|
return this._cache!;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Writes the given object to local storage.
|
||
|
*
|
||
|
* @param item the object to write to local storage
|
||
|
* @private
|
||
|
*/
|
||
|
private write(item: { [key: string]: string }): void {
|
||
|
this._cache = item;
|
||
|
localStorage.setItem(this.key, JSON.stringify(item));
|
||
|
}
|
||
|
|
||
|
|
||
|
/**
|
||
|
* Removes the data from storage.
|
||
|
*/
|
||
|
clear(): void {
|
||
|
this._cache = null;
|
||
|
localStorage.removeItem(this.key);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Retrieves a boolean from storage.
|
||
|
*
|
||
|
* @param name the name of the boolean to retrieve
|
||
|
* @param def the value to return if no boolean is stored with the given name
|
||
|
* @protected
|
||
|
*/
|
||
|
getBoolean(name: string, def: boolean = false): boolean {
|
||
|
return (this.read()[name] ?? `${def}`) === "true";
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Stores a boolean.
|
||
|
*
|
||
|
* @param name the name of the boolean to store
|
||
|
* @param value the boolean to store under the given name
|
||
|
* @protected
|
||
|
*/
|
||
|
setBoolean(name: string, value: boolean): void {
|
||
|
const item = this.read();
|
||
|
item[name] = "" + value;
|
||
|
this.write(item);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Retrieves a number from storage.
|
||
|
*
|
||
|
* @param name the name of the number to retrieve
|
||
|
* @param def the value to return if no number is stored with the given name
|
||
|
* @protected
|
||
|
*/
|
||
|
getNumber(name: string, def: number = 0): number {
|
||
|
return +(this.read()[name] ?? def);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Stores a number.
|
||
|
*
|
||
|
* @param name the name of the number to store
|
||
|
* @param value the number to store under the given name
|
||
|
* @protected
|
||
|
*/
|
||
|
setNumber(name: string, value: number): void {
|
||
|
const item = this.read();
|
||
|
item[name] = "" + value;
|
||
|
this.write(item);
|
||
|
}
|
||
|
}
|