2017-02-21 04:25:19 +11:00
|
|
|
import merge from 'lodash.merge'
|
|
|
|
import objectPath from 'object-path'
|
2017-03-07 18:43:48 +11:00
|
|
|
import localforage from 'localforage'
|
2017-03-09 03:59:12 +11:00
|
|
|
import { throttle, each } from 'lodash'
|
2017-02-21 04:25:19 +11:00
|
|
|
|
2017-04-10 00:30:21 +10:00
|
|
|
let loaded = false
|
|
|
|
|
2017-02-21 04:25:19 +11: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 18:43:48 +11:00
|
|
|
return localforage
|
2017-02-21 04:25:19 +11:00
|
|
|
})()
|
|
|
|
|
2017-02-21 04:38:18 +11:00
|
|
|
const defaultSetState = (key, state, storage) => {
|
2017-04-10 00:30:21 +10:00
|
|
|
if (!loaded) {
|
|
|
|
console.log('waiting for old state to be loaded...')
|
|
|
|
} else {
|
|
|
|
return storage.setItem(key, state)
|
|
|
|
}
|
2017-02-21 04:38:18 +11:00
|
|
|
}
|
|
|
|
|
2017-02-21 04:25:19 +11:00
|
|
|
export default function createPersistedState ({
|
2017-02-24 05:11:22 +11:00
|
|
|
key = 'vuex-lz',
|
2017-02-21 04:25:19 +11:00
|
|
|
paths = [],
|
|
|
|
getState = (key, storage) => {
|
2017-02-21 04:54:09 +11:00
|
|
|
let value = storage.getItem(key)
|
2017-03-07 18:43:48 +11:00
|
|
|
return value
|
2017-02-21 04:25:19 +11:00
|
|
|
},
|
2017-02-22 20:32:09 +11:00
|
|
|
setState = throttle(defaultSetState, 60000),
|
2017-02-21 04:25:19 +11:00
|
|
|
reducer = defaultReducer,
|
|
|
|
storage = defaultStorage,
|
|
|
|
subscriber = store => handler => store.subscribe(handler)
|
|
|
|
} = {}) {
|
|
|
|
return store => {
|
2017-03-07 18:43:48 +11:00
|
|
|
getState(key, storage).then((savedState) => {
|
2017-04-10 06:15:35 +10: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-09 03:59:12 +11:00
|
|
|
|
2017-04-10 06:15:35 +10:00
|
|
|
store.replaceState(
|
|
|
|
merge({}, store.state, savedState)
|
|
|
|
)
|
|
|
|
}
|
2017-07-02 21:07:35 +10:00
|
|
|
if (store.state.users.lastLoginName) {
|
|
|
|
store.dispatch('loginUser', {username: store.state.users.lastLoginName, password: 'xxx'})
|
|
|
|
}
|
2017-04-10 06:15:35 +10:00
|
|
|
loaded = true
|
|
|
|
} catch (e) {
|
|
|
|
console.log("Couldn't load state")
|
|
|
|
loaded = true
|
2017-03-07 18:43:48 +11:00
|
|
|
}
|
|
|
|
})
|
2017-02-21 04:25:19 +11:00
|
|
|
|
|
|
|
subscriber(store)((mutation, state) => {
|
|
|
|
try {
|
|
|
|
setState(key, reducer(state, paths), storage)
|
|
|
|
} catch (e) {
|
|
|
|
console.log("Couldn't persist state:")
|
|
|
|
console.log(e)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|