akkoma-fe/src/lib/persisted_state.js

93 lines
2.5 KiB
JavaScript
Raw Normal View History

import merge from 'lodash.merge'
import localforage from 'localforage'
2022-03-17 07:02:26 +00:00
import { each, get, set, cloneDeep } from 'lodash'
let loaded = false
const defaultReducer = (state, paths) => (
paths.length === 0 ? state : paths.reduce((substate, path) => {
set(substate, path, get(state, path))
return substate
}, {})
)
2018-09-07 15:17:17 +00:00
const saveImmedeatelyActions = [
'markNotificationsAsSeen',
'clearCurrentUser',
'setCurrentUser',
'setHighlight',
2018-10-26 13:16:23 +00:00
'setOption',
'setClientData',
'setToken',
'clearToken'
2018-09-07 15:17:17 +00:00
]
const defaultStorage = (() => {
return localforage
})()
export default function createPersistedState ({
key = 'vuex-lz',
paths = [],
getState = (key, storage) => {
2017-02-20 17:54:09 +00:00
let value = storage.getItem(key)
return value
},
2018-09-07 15:17:17 +00:00
setState = (key, state, storage) => {
if (!loaded) {
console.log('waiting for old state to be loaded...')
return Promise.resolve()
} else {
return storage.setItem(key, state)
}
},
reducer = defaultReducer,
storage = defaultStorage,
subscriber = store => handler => store.subscribe(handler)
} = {}) {
2018-10-26 13:16:23 +00:00
return getState(key, storage).then((savedState) => {
return store => {
try {
if (savedState !== null && 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
store.replaceState(
merge({}, store.state, savedState)
)
}
loaded = true
} catch (e) {
console.error("Couldn't load state")
console.error(e)
loaded = true
}
2018-10-26 13:16:23 +00:00
subscriber(store)((mutation, state) => {
try {
if (saveImmedeatelyActions.includes(mutation.type)) {
2022-03-17 07:02:26 +00:00
setState(key, reducer(cloneDeep(state), paths), storage)
2018-10-26 13:16:23 +00:00
.then(success => {
if (typeof success !== 'undefined') {
if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
2018-10-26 13:16:23 +00:00
store.dispatch('settingsSaved', { success })
}
}
}, error => {
if (mutation.type === 'setOption' || mutation.type === 'setCurrentUser') {
2018-10-26 13:16:23 +00:00
store.dispatch('settingsSaved', { error })
2018-09-07 15:17:17 +00:00
}
2018-10-26 13:16:23 +00:00
})
}
} catch (e) {
console.error("Couldn't persist state:")
console.error(e)
2018-09-07 15:17:17 +00:00
}
2018-10-26 13:16:23 +00:00
})
}
})
}