UNPKG

1.85 kBJavaScriptView Raw
1import { MemoryStorage, WebStorage } from './storage';
2
3// eslint-disable-next-line
4const _global = (typeof window !== 'undefined' ? window : global || {});
5
6/**
7 * @type {{install: (function(Object, Object): WebStorage)}}
8 */
9const VueStorage = {
10 /**
11 * Install plugin
12 *
13 * @param {Object} Vue
14 * @param {Object} options
15 * @returns {WebStorage}
16 */
17 install(Vue, options = {}) {
18 const _options = {
19 ...options,
20 storage: options.storage || 'local',
21 name: options.name || 'ls',
22 };
23
24 if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
25 throw new Error(`Vue-ls: Storage "${_options.storage}" is not supported`);
26 }
27
28 let store = null;
29
30 switch(_options.storage) { // eslint-disable-line
31 case 'local':
32 store = 'localStorage' in _global
33 ? _global.localStorage
34 : null
35 ;
36 break;
37
38 case 'session':
39 store = 'sessionStorage' in _global
40 ? _global.sessionStorage
41 : null
42 ;
43 break;
44 case 'memory':
45 store = MemoryStorage;
46 break;
47 }
48
49 if (!store) {
50 store = MemoryStorage;
51 // eslint-disable-next-line
52 console.error(`Vue-ls: Storage "${_options.storage}" is not supported your system, use memory storage`);
53 }
54
55 const ls = new WebStorage(store);
56
57 ls.setOptions(Object.assign(ls.options, {
58 namespace: '',
59 }, _options || {}));
60
61 Vue[_options.name] = ls; // eslint-disable-line
62 Object.defineProperty(Vue.prototype || Vue.config.globalProperties, `$${_options.name}`, {
63 /**
64 * Define $ls property
65 *
66 * @return {WebStorage}
67 */
68 get() {
69 return ls;
70 },
71 });
72 },
73};
74
75// eslint-disable-next-line
76_global.VueStorage = VueStorage;
77
78export default VueStorage;