all files / src/ vuexplugin.ts

100% Statements 24/24
100% Branches 4/4
100% Functions 3/3
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36                           
import { Store, VuexPlugin, Option } from './interfaces'
import { copy } from './objpath'
import LSStorage from './lsstorage'
 
import assign from './assign'
 
/**
 * Create Vuex plugin
 */
export function createVuexPlugin(option: Option): VuexPlugin<Object> {
	const ls = new LSStorage(option)
	const { keys, merge = assign, namespace: ns } = option
	return (store: Store<Object>) => {
		let data = null
		if (ls.has(ns)) {
			data = ls.get(ns)
		} else {
			const obj = {}
			for (const k of keys) {
				copy(obj, store.state, k)
			}
			data = obj
		}
		store.replaceState(merge(store.state, data)) //merge state
		ls.set(ns, data)
		store.subscribe((mutation, state) => {
			const obj = {}
			for (const k of keys) {
				copy(obj, state, k)
			}
			data = obj
			ls.set(ns, obj)
		})
	}
}