2019-12-08 00:32:00 +05:30
|
|
|
import logger from 'app/services/logger';
|
2017-04-12 00:48:27 +05:30
|
|
|
|
|
|
|
let _hasStorage = false;
|
|
|
|
|
|
|
|
try {
|
2019-11-27 14:33:32 +05:30
|
|
|
const test = 'test';
|
|
|
|
window.localStorage.setItem(test, test);
|
|
|
|
window.localStorage.removeItem(test);
|
2017-04-12 00:48:27 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
_hasStorage = true;
|
2017-04-12 00:48:27 +05:30
|
|
|
} catch (err) {
|
2019-11-27 14:33:32 +05:30
|
|
|
// bad luck, no storage available
|
|
|
|
logger.info('No storage available'); // log for statistic purposes
|
2017-04-12 00:48:27 +05:30
|
|
|
}
|
|
|
|
|
2020-01-18 02:07:52 +05:30
|
|
|
export function hasStorage(): boolean {
|
2019-11-27 14:33:32 +05:30
|
|
|
return _hasStorage;
|
2017-04-12 00:48:27 +05:30
|
|
|
}
|
|
|
|
|
2020-01-17 15:14:22 +05:30
|
|
|
class DummyStorage implements Storage {
|
2020-01-18 02:07:52 +05:30
|
|
|
[name: string]: any;
|
|
|
|
|
|
|
|
readonly length: number;
|
|
|
|
|
2020-01-17 15:14:22 +05:30
|
|
|
getItem(key: string): string | null {
|
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 {
|
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);
|
|
|
|
}
|
2020-01-18 02:07:52 +05:30
|
|
|
|
|
|
|
clear(): void {
|
|
|
|
Object.keys(this).forEach(this.removeItem);
|
|
|
|
}
|
|
|
|
|
|
|
|
key(index: number): string | null {
|
|
|
|
return Object.keys(this)[index] || null;
|
|
|
|
}
|
2017-04-12 00:48:27 +05:30
|
|
|
}
|
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
export const localStorage = _hasStorage
|
|
|
|
? window.localStorage
|
|
|
|
: new DummyStorage();
|
2017-04-12 00:48:27 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
export const sessionStorage = _hasStorage
|
|
|
|
? window.sessionStorage
|
|
|
|
: new DummyStorage();
|
2017-04-12 00:48:27 +05:30
|
|
|
|
|
|
|
export default localStorage;
|