2017-02-20 17:25:19 +00:00
|
|
|
import merge from 'lodash.merge'
|
|
|
|
import objectPath from 'object-path'
|
2017-03-07 07:43:48 +00:00
|
|
|
import localforage from 'localforage'
|
2017-02-20 17:38:18 +00:00
|
|
|
import { throttle } from 'lodash'
|
2017-02-20 17:25:19 +00:00
|
|
|
|
|
|
|
const defaultReducer = (state, paths) => (
|
|
|
|
paths.length === 0 ? state : paths.reduce((substate, path) => {
|
|
|
|
objectPath.set(substate, path, objectPath.get(state, path))
|
|
|
|
return substate
|
|
|
|
}, {})
|
|
|
|
)
|
|
|
|
|
|
|
|
const defaultStorage = (() => {
|
2017-03-07 07:43:48 +00:00
|
|
|
return localforage
|
2017-02-20 17:25:19 +00:00
|
|
|
})()
|
|
|
|
|
2017-02-20 17:38:18 +00:00
|
|
|
const defaultSetState = (key, state, storage) => {
|
2017-03-07 07:43:48 +00:00
|
|
|
return storage.setItem(key, state)
|
2017-02-20 17:38:18 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 17:25:19 +00:00
|
|
|
export default function createPersistedState ({
|
2017-02-23 18:11:22 +00:00
|
|
|
key = 'vuex-lz',
|
2017-02-20 17:25:19 +00:00
|
|
|
paths = [],
|
|
|
|
getState = (key, storage) => {
|
2017-02-20 17:54:09 +00:00
|
|
|
let value = storage.getItem(key)
|
2017-03-07 07:43:48 +00:00
|
|
|
return value
|
2017-02-20 17:25:19 +00:00
|
|
|
},
|
2017-02-22 09:32:09 +00:00
|
|
|
setState = throttle(defaultSetState, 60000),
|
2017-02-20 17:25:19 +00:00
|
|
|
reducer = defaultReducer,
|
|
|
|
storage = defaultStorage,
|
|
|
|
subscriber = store => handler => store.subscribe(handler)
|
|
|
|
} = {}) {
|
|
|
|
return store => {
|
2017-03-07 07:43:48 +00:00
|
|
|
getState(key, storage).then((savedState) => {
|
|
|
|
if (typeof savedState === 'object') {
|
|
|
|
store.replaceState(
|
|
|
|
merge({}, store.state, savedState)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
})
|
2017-02-20 17:25:19 +00:00
|
|
|
|
|
|
|
subscriber(store)((mutation, state) => {
|
|
|
|
try {
|
|
|
|
setState(key, reducer(state, paths), storage)
|
|
|
|
} catch (e) {
|
|
|
|
console.log("Couldn't persist state:")
|
|
|
|
console.log(e)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|