accounts-frontend/packages/app/services/localStorage.ts

60 lines
1.2 KiB
TypeScript
Raw Normal View History

import logger from 'app/services/logger';
let _hasStorage = false;
try {
const test = 'test';
window.localStorage.setItem(test, test);
window.localStorage.removeItem(test);
_hasStorage = true;
} catch (err) {
// bad luck, no storage available
logger.info('No storage available'); // log for statistic purposes
}
export function hasStorage(): boolean {
return _hasStorage;
}
2020-01-17 15:14:22 +05:30
class DummyStorage implements Storage {
2020-05-20 21:59:48 +05:30
// FIXME: we can't use this declaration because it breaks react-hot-loader/babel
// [key: string]: any;
2020-05-20 21:59:48 +05:30
get length() {
return Object.keys(this).length;
}
2020-01-17 15:14:22 +05:30
getItem(key: string): string | null {
2020-05-20 21:59:48 +05:30
// @ts-ignore
2019-12-07 16:58:52 +05:30
return this[key] || null;
}
2020-01-17 15:14:22 +05:30
setItem(key: string, value: string): void {
2020-05-20 21:59:48 +05:30
// @ts-ignore
2019-12-07 16:58:52 +05:30
this[key] = value;
}
2020-01-17 15:14:22 +05:30
removeItem(key: string): void {
2019-12-07 16:58:52 +05:30
Reflect.deleteProperty(this, key);
}
clear(): void {
Object.keys(this).forEach(this.removeItem);
}
key(index: number): string | null {
return Object.keys(this)[index] || null;
}
}
export const localStorage = _hasStorage
? window.localStorage
: new DummyStorage();
export const sessionStorage = _hasStorage
? window.sessionStorage
: new DummyStorage();
export default localStorage;