aboutsummaryrefslogtreecommitdiff
path: root/src/lib/persisted_state.js
blob: de1e5383d16653a13387e3b7fe06fc95a382796e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import merge from 'lodash.merge'
import objectPath from 'object-path'
import { throttle } from 'lodash'
import { inflate, deflate } from 'pako'

const defaultReducer = (state, paths) => (
  paths.length === 0 ? state : paths.reduce((substate, path) => {
    objectPath.set(substate, path, objectPath.get(state, path))
    return substate
  }, {})
)

const defaultStorage = (() => {
  const hasLocalStorage = typeof window !== 'undefined' && window.localStorage
  if (hasLocalStorage) {
    return window.localStorage
  }

  class InternalStorage {
    setItem (key, item) {
      this[key] = item
      return item
    }
    getItem (key) {
      return this[key]
    }
    removeItem (key) {
      delete this[key]
    }
    clear () {
      Object.keys(this).forEach(key => delete this[key])
    }
  }

  return new InternalStorage()
})()

const defaultSetState = (key, state, storage) => {
  return storage.setItem(key, deflate(JSON.stringify(state), { to: 'string' }))
}

export default function createPersistedState ({
  key = 'vuex',
  paths = [],
  getState = (key, storage) => {
    let value = storage.getItem(key)
    try {
      value = inflate(value, { to: 'string' })
    } catch (e) {
      console.log("Couldn't inflate value... Maybe upgrading")
    }
    return value && value !== 'undefined' ? JSON.parse(value) : undefined
  },
  setState = throttle(defaultSetState, 5000),
  reducer = defaultReducer,
  storage = defaultStorage,
  subscriber = store => handler => store.subscribe(handler)
} = {}) {
  return store => {
    const savedState = getState(key, storage)
    if (typeof savedState === 'object') {
      store.replaceState(
        merge({}, store.state, savedState)
      )
    }

    subscriber(store)((mutation, state) => {
      try {
        setState(key, reducer(state, paths), storage)
      } catch (e) {
        console.log("Couldn't persist state:")
        console.log(e)
      }
    })
  }
}