UNPKG

12.4 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.VueStorage = factory());
5}(this, (function () { 'use strict';
6
7 function _classCallCheck(instance, Constructor) {
8 if (!(instance instanceof Constructor)) {
9 throw new TypeError("Cannot call a class as a function");
10 }
11 }
12
13 function _defineProperties(target, props) {
14 for (var i = 0; i < props.length; i++) {
15 var descriptor = props[i];
16 descriptor.enumerable = descriptor.enumerable || false;
17 descriptor.configurable = true;
18 if ("value" in descriptor) descriptor.writable = true;
19 Object.defineProperty(target, descriptor.key, descriptor);
20 }
21 }
22
23 function _createClass(Constructor, protoProps, staticProps) {
24 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
25 if (staticProps) _defineProperties(Constructor, staticProps);
26 return Constructor;
27 }
28
29 function _defineProperty(obj, key, value) {
30 if (key in obj) {
31 Object.defineProperty(obj, key, {
32 value: value,
33 enumerable: true,
34 configurable: true,
35 writable: true
36 });
37 } else {
38 obj[key] = value;
39 }
40
41 return obj;
42 }
43
44 function ownKeys(object, enumerableOnly) {
45 var keys = Object.keys(object);
46
47 if (Object.getOwnPropertySymbols) {
48 var symbols = Object.getOwnPropertySymbols(object);
49 if (enumerableOnly) symbols = symbols.filter(function (sym) {
50 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
51 });
52 keys.push.apply(keys, symbols);
53 }
54
55 return keys;
56 }
57
58 function _objectSpread2(target) {
59 for (var i = 1; i < arguments.length; i++) {
60 var source = arguments[i] != null ? arguments[i] : {};
61
62 if (i % 2) {
63 ownKeys(Object(source), true).forEach(function (key) {
64 _defineProperty(target, key, source[key]);
65 });
66 } else if (Object.getOwnPropertyDescriptors) {
67 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
68 } else {
69 ownKeys(Object(source)).forEach(function (key) {
70 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
71 });
72 }
73 }
74
75 return target;
76 }
77
78 /* eslint class-methods-use-this: off */
79 var ls = {};
80
81 var MemoryStorageInterface = /*#__PURE__*/function () {
82 function MemoryStorageInterface() {
83 _classCallCheck(this, MemoryStorageInterface);
84
85 Object.defineProperty(this, 'length', {
86 /**
87 * Define length property
88 *
89 * @return {number}
90 */
91 get: function get() {
92 return Object.keys(ls).length;
93 }
94 });
95 }
96 /**
97 * Get item
98 *
99 * @param {string} name
100 * @returns {*}
101 */
102
103
104 _createClass(MemoryStorageInterface, [{
105 key: "getItem",
106 value: function getItem(name) {
107 return name in ls ? ls[name] : null;
108 }
109 /**
110 * Set item
111 *
112 * @param {string} name
113 * @param {*} value
114 * @returns {boolean}
115 */
116
117 }, {
118 key: "setItem",
119 value: function setItem(name, value) {
120 ls[name] = value;
121 return true;
122 }
123 /**
124 * Remove item
125 *
126 * @param {string} name
127 * @returns {boolean}
128 */
129
130 }, {
131 key: "removeItem",
132 value: function removeItem(name) {
133 var found = (name in ls);
134
135 if (found) {
136 return delete ls[name];
137 }
138
139 return false;
140 }
141 /**
142 * Clear storage
143 *
144 * @returns {boolean}
145 */
146
147 }, {
148 key: "clear",
149 value: function clear() {
150 ls = {};
151 return true;
152 }
153 /**
154 * Get item by key
155 *
156 * @param {number} index
157 * @returns {*}
158 */
159
160 }, {
161 key: "key",
162 value: function key(index) {
163 var keys = Object.keys(ls);
164 return typeof keys[index] !== 'undefined' ? keys[index] : null;
165 }
166 }]);
167
168 return MemoryStorageInterface;
169 }();
170
171 var MemoryStorage = new MemoryStorageInterface();
172
173 var listeners = {};
174 /**
175 * Event class
176 */
177
178 var WebStorageEvent = /*#__PURE__*/function () {
179 function WebStorageEvent() {
180 _classCallCheck(this, WebStorageEvent);
181 }
182
183 _createClass(WebStorageEvent, null, [{
184 key: "on",
185
186 /**
187 * Add storage change event
188 *
189 * @param {string} name
190 * @param {Function} callback
191 */
192 value: function on(name, callback) {
193 if (typeof listeners[name] === 'undefined') {
194 listeners[name] = [];
195 }
196
197 listeners[name].push(callback);
198 }
199 /**
200 * Remove storage change event
201 *
202 * @param {string} name
203 * @param {Function} callback
204 */
205
206 }, {
207 key: "off",
208 value: function off(name, callback) {
209 if (listeners[name].length) {
210 listeners[name].splice(listeners[name].indexOf(callback), 1);
211 } else {
212 listeners[name] = [];
213 }
214 }
215 /**
216 * Emit event
217 *
218 * @param {Object} event
219 */
220
221 }, {
222 key: "emit",
223 value: function emit(event) {
224 var e = event || window.event;
225
226 var getValue = function getValue(data) {
227 try {
228 return JSON.parse(data).value;
229 } catch (err) {
230 return data;
231 }
232 };
233
234 var fire = function fire(listener) {
235 var newValue = getValue(e.newValue);
236 var oldValue = getValue(e.oldValue);
237 listener(newValue, oldValue, e.url || e.uri);
238 };
239
240 if (typeof e === 'undefined' || typeof e.key === 'undefined') {
241 return;
242 }
243
244 var all = listeners[e.key];
245
246 if (typeof all !== 'undefined') {
247 all.forEach(fire);
248 }
249 }
250 }]);
251
252 return WebStorageEvent;
253 }();
254
255 /**
256 * Storage Bridge
257 */
258
259 var WebStorage = /*#__PURE__*/function () {
260 /**
261 * @param {Object} storage
262 */
263 function WebStorage(storage) {
264 _classCallCheck(this, WebStorage);
265
266 this.storage = storage;
267 this.options = {
268 namespace: '',
269 events: ['storage']
270 };
271 Object.defineProperty(this, 'length', {
272 /**
273 * Define length property
274 *
275 * @return {number}
276 */
277 get: function get() {
278 return this.storage.length;
279 }
280 });
281
282 if (typeof window !== 'undefined') {
283 for (var i in this.options.events) {
284 if (window.addEventListener) {
285 window.addEventListener(this.options.events[i], WebStorageEvent.emit, false);
286 } else if (window.attachEvent) {
287 window.attachEvent("on".concat(this.options.events[i]), WebStorageEvent.emit);
288 } else {
289 window["on".concat(this.options.events[i])] = WebStorageEvent.emit;
290 }
291 }
292 }
293 }
294 /**
295 * Set Options
296 *
297 * @param {Object} options
298 */
299
300
301 _createClass(WebStorage, [{
302 key: "setOptions",
303 value: function setOptions() {
304 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
305 this.options = Object.assign(this.options, options);
306 }
307 /**
308 * Set item
309 *
310 * @param {string} name
311 * @param {*} value
312 * @param {number} expire - seconds
313 */
314
315 }, {
316 key: "set",
317 value: function set(name, value) {
318 var expire = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
319 var stringifyValue = JSON.stringify({
320 value: value,
321 expire: expire !== null ? new Date().getTime() + expire : null
322 });
323 this.storage.setItem(this.options.namespace + name, stringifyValue);
324 }
325 /**
326 * Get item
327 *
328 * @param {string} name
329 * @param {*} def - default value
330 * @returns {*}
331 */
332
333 }, {
334 key: "get",
335 value: function get(name) {
336 var def = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
337 var item = this.storage.getItem(this.options.namespace + name);
338
339 if (item !== null) {
340 try {
341 var data = JSON.parse(item);
342
343 if (data.expire === null) {
344 return data.value;
345 }
346
347 if (data.expire >= new Date().getTime()) {
348 return data.value;
349 }
350
351 this.remove(name);
352 } catch (err) {
353 return def;
354 }
355 }
356
357 return def;
358 }
359 /**
360 * Get item by key
361 *
362 * @param {number} index
363 * @return {*}
364 */
365
366 }, {
367 key: "key",
368 value: function key(index) {
369 return this.storage.key(index);
370 }
371 /**
372 * Remove item
373 *
374 * @param {string} name
375 * @return {boolean}
376 */
377
378 }, {
379 key: "remove",
380 value: function remove(name) {
381 return this.storage.removeItem(this.options.namespace + name);
382 }
383 /**
384 * Clear storage
385 */
386
387 }, {
388 key: "clear",
389 value: function clear() {
390 if (this.length === 0) {
391 return;
392 }
393
394 var removedKeys = [];
395
396 for (var i = 0; i < this.length; i++) {
397 var key = this.storage.key(i);
398 var regexp = new RegExp("^".concat(this.options.namespace, ".+"), 'i');
399
400 if (regexp.test(key) === false) {
401 continue;
402 }
403
404 removedKeys.push(key);
405 }
406
407 for (var _key in removedKeys) {
408 this.storage.removeItem(removedKeys[_key]);
409 }
410 }
411 /**
412 * Add storage change event
413 *
414 * @param {string} name
415 * @param {Function} callback
416 */
417
418 }, {
419 key: "on",
420 value: function on(name, callback) {
421 WebStorageEvent.on(this.options.namespace + name, callback);
422 }
423 /**
424 * Remove storage change event
425 *
426 * @param {string} name
427 * @param {Function} callback
428 */
429
430 }, {
431 key: "off",
432 value: function off(name, callback) {
433 WebStorageEvent.off(this.options.namespace + name, callback);
434 }
435 }]);
436
437 return WebStorage;
438 }();
439
440 var _global = typeof window !== 'undefined' ? window : global || {};
441 /**
442 * @type {{install: (function(Object, Object): WebStorage)}}
443 */
444
445
446 var VueStorage = {
447 /**
448 * Install plugin
449 *
450 * @param {Object} Vue
451 * @param {Object} options
452 * @returns {WebStorage}
453 */
454 install: function install(Vue) {
455 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
456
457 var _options = _objectSpread2(_objectSpread2({}, options), {}, {
458 storage: options.storage || 'local',
459 name: options.name || 'ls'
460 });
461
462 if (_options.storage && ['memory', 'local', 'session'].indexOf(_options.storage) === -1) {
463 throw new Error("Vue-ls: Storage \"".concat(_options.storage, "\" is not supported"));
464 }
465
466 var store = null;
467
468 switch (_options.storage) {
469 // eslint-disable-line
470 case 'local':
471 store = 'localStorage' in _global ? _global.localStorage : null;
472 break;
473
474 case 'session':
475 store = 'sessionStorage' in _global ? _global.sessionStorage : null;
476 break;
477
478 case 'memory':
479 store = MemoryStorage;
480 break;
481 }
482
483 if (!store) {
484 store = MemoryStorage; // eslint-disable-next-line
485
486 console.error("Vue-ls: Storage \"".concat(_options.storage, "\" is not supported your system, use memory storage"));
487 }
488
489 var ls = new WebStorage(store);
490 ls.setOptions(Object.assign(ls.options, {
491 namespace: ''
492 }, _options || {}));
493 Vue[_options.name] = ls; // eslint-disable-line
494
495 Object.defineProperty(Vue.prototype || Vue.config.globalProperties, "$".concat(_options.name), {
496 /**
497 * Define $ls property
498 *
499 * @return {WebStorage}
500 */
501 get: function get() {
502 return ls;
503 }
504 });
505 }
506 }; // eslint-disable-next-line
507
508 _global.VueStorage = VueStorage;
509
510 return VueStorage;
511
512})));