all files / src/ vuexplugin.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 3/3
100% Lines 18/18
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          10× 10×                
import { Store, VuexPlugin, Option } from './interfaces'
import { copy } from './objpath'
import { localStorage } from './drivers'
import defaultMerge from './merge'
 
/**
 * Create Vuex plugin
 */
export function createVuexPlugin(option: Option): VuexPlugin<object> {
	const { keys, merge = defaultMerge, namespace: ns, driver = localStorage } = option
	return (store: Store<object>) => {
		if (driver.has(ns)) {
			const data = driver.get(ns)
			store.replaceState(merge(store.state, data))
		} else {
			const data = {}
			for (const k of keys) {
				copy(data, store.state, k)
			}
			driver.set(ns, data)
		}
		store.subscribe((mutation, state) => {
			const data = {}
			for (const k of keys) {
				copy(data, state, k)
			}
			driver.set(ns, data)
		})
	}
}