From dcf95410d72c0af6df7b7b411bb622097a2cb0b3 Mon Sep 17 00:00:00 2001 From: SleepWalker Date: Tue, 11 Apr 2017 22:18:27 +0300 Subject: [PATCH] #316: add localStorage wrapper with feature detection --- .eslintrc.json | 4 ++++ src/components/auth/actions.js | 1 + src/services/authFlow/AuthFlow.js | 1 + src/services/localStorage.js | 40 +++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+) create mode 100644 src/services/localStorage.js diff --git a/.eslintrc.json b/.eslintrc.json index 52b86a3..040f151 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -113,6 +113,10 @@ "no-undef-init": "error", "no-undef": "error", "no-use-before-define": ["warn", "nofunc"], + "no-restricted-globals": ["error", + "localStorage", "sessionStorage", // we have our own localStorage module + "event" + ], // CommonJS "no-mixed-requires": "warn", diff --git a/src/components/auth/actions.js b/src/components/auth/actions.js index 58f78bb..68701df 100644 --- a/src/components/auth/actions.js +++ b/src/components/auth/actions.js @@ -1,6 +1,7 @@ import { routeActions } from 'react-router-redux'; import logger from 'services/logger'; +import localStorage from 'services/localStorage'; import loader from 'services/loader'; import history from 'services/history'; import { updateUser, acceptRules as userAcceptRules } from 'components/user/actions'; diff --git a/src/services/authFlow/AuthFlow.js b/src/services/authFlow/AuthFlow.js index 75806c1..2ed6fb8 100644 --- a/src/services/authFlow/AuthFlow.js +++ b/src/services/authFlow/AuthFlow.js @@ -1,6 +1,7 @@ import { routeActions } from 'react-router-redux'; import logger from 'services/logger'; +import localStorage from 'services/localStorage'; import RegisterState from './RegisterState'; import LoginState from './LoginState'; diff --git a/src/services/localStorage.js b/src/services/localStorage.js new file mode 100644 index 0000000..bc3e98b --- /dev/null +++ b/src/services/localStorage.js @@ -0,0 +1,40 @@ +import logger from '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() { + return _hasStorage; +} + +function DummyStorage() { + return { + getItem(key) { + return this[key] || null; + }, + + setItem(key, value) { + this[key] = value; + }, + + removeItem(key) { + Reflect.deleteProperty(this, key); + } + }; +} + +export const localStorage = _hasStorage ? window.localStorage : new DummyStorage(); + +export const sessionStorage = _hasStorage ? window.sessionStorage : new DummyStorage(); + +export default localStorage;