2019-04-03 04:41:08 -05:00
|
|
|
type StoreValue = string | number | boolean | null;
|
|
|
|
|
2017-10-24 09:13:49 -05:00
|
|
|
export class Store {
|
2019-04-03 04:41:08 -05:00
|
|
|
get(key: string) {
|
2017-10-24 09:13:49 -05:00
|
|
|
return window.localStorage[key];
|
|
|
|
}
|
|
|
|
|
2019-04-03 04:41:08 -05:00
|
|
|
set(key: string, value: StoreValue) {
|
2017-10-24 09:13:49 -05:00
|
|
|
window.localStorage[key] = value;
|
|
|
|
}
|
|
|
|
|
2019-12-11 09:11:32 -06:00
|
|
|
getBool(key: string, def: boolean): boolean {
|
2017-10-24 09:13:49 -05:00
|
|
|
if (def !== void 0 && !this.exists(key)) {
|
|
|
|
return def;
|
|
|
|
}
|
2017-12-20 05:33:33 -06:00
|
|
|
return window.localStorage[key] === 'true';
|
2017-10-24 09:13:49 -05:00
|
|
|
}
|
|
|
|
|
2018-08-02 09:43:33 -05:00
|
|
|
getObject(key: string, def?: any) {
|
|
|
|
let ret = def;
|
|
|
|
if (this.exists(key)) {
|
|
|
|
const json = window.localStorage[key];
|
|
|
|
try {
|
|
|
|
ret = JSON.parse(json);
|
|
|
|
} catch (error) {
|
|
|
|
console.error(`Error parsing store object: ${key}. Returning default: ${def}. [${error}]`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2020-04-20 08:13:02 -05:00
|
|
|
/* Returns true when successfully stored, throws error if not successfully stored */
|
|
|
|
setObject(key: string, value: any) {
|
2018-08-02 09:43:33 -05:00
|
|
|
let json;
|
|
|
|
try {
|
|
|
|
json = JSON.stringify(value);
|
|
|
|
} catch (error) {
|
2020-04-20 08:13:02 -05:00
|
|
|
throw new Error(`Could not stringify object: ${key}. [${error}]`);
|
2018-08-02 09:43:33 -05:00
|
|
|
}
|
|
|
|
try {
|
|
|
|
this.set(key, json);
|
|
|
|
} catch (error) {
|
|
|
|
// Likely hitting storage quota
|
2021-10-11 02:48:25 -05:00
|
|
|
const errorToThrow = new Error(`Could not save item in localStorage: ${key}. [${error}]`);
|
|
|
|
errorToThrow.name = error.name;
|
|
|
|
throw errorToThrow;
|
2018-08-02 09:43:33 -05:00
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-04-03 04:41:08 -05:00
|
|
|
exists(key: string) {
|
2017-10-24 09:13:49 -05:00
|
|
|
return window.localStorage[key] !== void 0;
|
|
|
|
}
|
|
|
|
|
2019-04-03 04:41:08 -05:00
|
|
|
delete(key: string) {
|
2017-10-24 09:13:49 -05:00
|
|
|
window.localStorage.removeItem(key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const store = new Store();
|
|
|
|
export default store;
|