getStorage.js.flow 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // @flow
  2. import type { Storage } from '../types'
  3. function noop() {}
  4. let noopStorage = {
  5. getItem: noop,
  6. setItem: noop,
  7. removeItem: noop,
  8. }
  9. function hasStorage(storageType) {
  10. if (typeof self !== 'object' || !(storageType in self)) {
  11. return false
  12. }
  13. try {
  14. let storage = self[storageType]
  15. const testKey = `redux-persist ${storageType} test`
  16. storage.setItem(testKey, 'test')
  17. storage.getItem(testKey)
  18. storage.removeItem(testKey)
  19. } catch (e) {
  20. if (process.env.NODE_ENV !== 'production')
  21. console.warn(
  22. `redux-persist ${storageType} test failed, persistence will be disabled.`
  23. )
  24. return false
  25. }
  26. return true
  27. }
  28. export default function getStorage(type: string): Storage {
  29. const storageType = `${type}Storage`
  30. if (hasStorage(storageType)) return self[storageType]
  31. else {
  32. if (process.env.NODE_ENV !== 'production') {
  33. console.error(
  34. `redux-persist failed to create sync storage. falling back to noop storage.`
  35. )
  36. }
  37. return noopStorage
  38. }
  39. }