UNPKG

1.79 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 = Object.assign({}, options, {
19 storage: options.storage || 'local',
20 name: options.name || 'ls',
21 });
22
23 if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
24 throw new Error(`Vue-ls: Storage "${_options.storage}" is not supported`);
25 }
26
27 let store = null;
28
29 switch(_options.storage) { // eslint-disable-line
30 case 'local':
31 store = 'localStorage' in _global
32 ? _global.localStorage
33 : null
34 ;
35 break;
36
37 case 'session':
38 store = 'sessionStorage' in _global
39 ? _global.sessionStorage
40 : null
41 ;
42 break;
43 case 'memory': store = MemoryStorage;
44 break;
45 }
46
47 if (!store) {
48 store = MemoryStorage;
49 // eslint-disable-next-line
50 console.error(`Vue-ls: Storage "${_options.storage}" is not supported your system, use memory storage`);
51 }
52
53 const ls = new WebStorage(store);
54
55 ls.setOptions(Object.assign(ls.options, {
56 namespace: '',
57 }, _options || {}));
58
59 Vue[_options.name] = ls; // eslint-disable-line
60 Object.defineProperty(Vue.prototype, `$${_options.name}`, {
61 /**
62 * Define $ls property
63 *
64 * @return {WebStorage}
65 */
66 get() {
67 return ls;
68 },
69 });
70 },
71};
72
73_global.VueStorage = VueStorage;
74
75export default VueStorage;