|
@@ -4,6 +4,8 @@ import { createObservable } from './observable'
|
|
const Spruce = {
|
|
const Spruce = {
|
|
stores: {},
|
|
stores: {},
|
|
|
|
|
|
|
|
+ persistenceDriver: window.localStorage,
|
|
|
|
+
|
|
persisted: [],
|
|
persisted: [],
|
|
|
|
|
|
subscribers: [],
|
|
subscribers: [],
|
|
@@ -95,13 +97,13 @@ const Spruce = {
|
|
},
|
|
},
|
|
|
|
|
|
retrieveFromLocalStorage(name, methods = {}) {
|
|
retrieveFromLocalStorage(name, methods = {}) {
|
|
- const storage = JSON.parse(window.localStorage.getItem(`__spruce:${name}`))
|
|
|
|
|
|
+ const storage = JSON.parse(this.persistenceDriver.getItem(`__spruce:${name}`))
|
|
|
|
|
|
return storage ? Object.assign(methods, storage) : null
|
|
return storage ? Object.assign(methods, storage) : null
|
|
},
|
|
},
|
|
|
|
|
|
updateLocalStorage(name) {
|
|
updateLocalStorage(name) {
|
|
- window.localStorage.setItem(`__spruce:${name}`, JSON.stringify(this.store(name)))
|
|
|
|
|
|
+ this.persistenceDriver.setItem(`__spruce:${name}`, JSON.stringify(this.store(name)))
|
|
},
|
|
},
|
|
|
|
|
|
watch(name, callback) {
|
|
watch(name, callback) {
|
|
@@ -134,6 +136,22 @@ const Spruce = {
|
|
return comparison[part]
|
|
return comparison[part]
|
|
}, stores)
|
|
}, stores)
|
|
})
|
|
})
|
|
|
|
+ },
|
|
|
|
+
|
|
|
|
+ persistUsing(driver) {
|
|
|
|
+ if (this.persisted.length > 0) {
|
|
|
|
+ console.warn('[Spruce] You have already initialised a persisted store. Changing the driver may cause issues.')
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if (typeof driver.getItem !== 'function') {
|
|
|
|
+ throw new Error('[Spruce] The persistence driver must have a `getItem(key)` method.')
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if (typeof driver.setItem !== 'function') {
|
|
|
|
+ throw new Error('[Spruce] The persistence driver must have a `setItem(key, value)` method.')
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ this.persistenceDriver = driver
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|