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-03-08 16:59:12 +00:00
|
|
|
import { throttle, each } from 'lodash'
|
2017-02-20 17:25:19 +00:00
|
|
|
|
2017-04-09 14:30:21 +00:00
|
|
|
let loaded = false
|
|
|
|
|
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-04-09 14:30:21 +00:00
|
|
|
if (!loaded) {
|
|
|
|
console.log('waiting for old state to be loaded...')
|
|
|
|
} else {
|
|
|
|
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) => {
|
2017-04-09 20:15:35 +00:00
|
|
|
try {
|
|
|
|
if (typeof savedState === 'object') {
|
|
|
|
// build user cache
|
|
|
|
const usersState = savedState.users || {}
|
|
|
|
usersState.usersObject = {}
|
|
|
|
const users = usersState.users || []
|
|
|
|
each(users, (user) => { usersState.usersObject[user.id] = user })
|
|
|
|
savedState.users = usersState
|
2017-03-08 16:59:12 +00:00
|
|
|
|
2017-04-09 20:15:35 +00:00
|
|
|
store.replaceState(
|
|
|
|
merge({}, store.state, savedState)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
loaded = true
|
|
|
|
} catch (e) {
|
|
|
|
console.log("Couldn't load state")
|
|
|
|
loaded = true
|
2017-03-07 07:43:48 +00:00
|
|
|
}
|
|
|
|
})
|
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)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|