aboutsummaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
authorRoger Braun <roger@rogerbraun.net>2017-02-20 18:25:19 +0100
committerRoger Braun <roger@rogerbraun.net>2017-02-20 18:25:19 +0100
commitebf9fe6a987842966d32f881902f233a67787d2f (patch)
tree96b7c3c03088c096e943a7621a6b09e098cc4d9e /src/lib
parent9763009d8616765ce87f1dcf8d22e935c45a22c8 (diff)
Pull in persistence plugin, don't blow up on full storage.
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/persisted_state.js65
1 files changed, 65 insertions, 0 deletions
diff --git a/src/lib/persisted_state.js b/src/lib/persisted_state.js
new file mode 100644
index 00000000..67ecc1ea
--- /dev/null
+++ b/src/lib/persisted_state.js
@@ -0,0 +1,65 @@
+import merge from 'lodash.merge'
+import objectPath from 'object-path'
+
+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()
+})()
+
+export default function createPersistedState ({
+ key = 'vuex',
+ paths = [],
+ getState = (key, storage) => {
+ const value = storage.getItem(key)
+ return value && value !== 'undefined' ? JSON.parse(value) : undefined
+ },
+ setState = (key, state, storage) => storage.setItem(key, JSON.stringify(state)),
+ 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)
+ }
+ })
+ }
+}