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