UNPKG

ss-storage

Version:

SS Storage is library that help to store data in the session storage, or retrieve data

90 lines (89 loc) 2.89 kB
"use strict"; exports.__esModule = true; var storage = { /** * The get method retrieves a value from the storage. * @param {string} key The key identifier of data to get * @returns The current value associated with the given key, or null if the given key does not exist in the list associated with the object. */ get: function (key) { if (!key) { console.error("Key is missing"); return null; } if (!window.sessionStorage.getItem(key)) return null; try { var values = JSON.parse(window.sessionStorage.getItem(key)); // We return data if the exist in the storage object if (values === null || values === void 0 ? void 0 : values.data) return values.data; } catch (e) { // On error we will remove the key from the storage // And return null this.remove(key); } return null; }, /** * Sets the value of the pair identified by key to value, * creating a new key/value pair if none existed for key previously. * @param {string} key The key identifier of data to set * @param {any} value The value to store * @returns The value if set, or null if not set */ set: function (key, value) { if (!value || value == {} || (Array.isArray(value) && !value.length)) { this.remove(key); return null; } var now = new Date().getTime(); var _value = { data: value, time: now }; try { window.sessionStorage.setItem(key, JSON.stringify(_value)); return value; } catch (e) { console.error(e); return null; } }, /** * Removes the key/value pair with the given key, * if a key/value pair with the given key exists. * @param {key} string The key identifier of data to remove * @returns {boolean} {value} if the data was removed */ remove: function (key) { window.sessionStorage.removeItem(key); }, /** * Removes all key/value pairs, if there are any. */ clear: function () { window.sessionStorage.clear(); } }; if (typeof sessionStorage === "undefined" || sessionStorage === null) { storage = { get: function (key) { console.warn("sessionStorage is not defined"); return key; }, set: function (key, value) { console.warn("sessionStorage is not defined"); return { key: key, value: value }; }, remove: function () { console.warn("sessionStorage is not defined"); }, clear: function () { console.warn("sessionStorage is not defined"); } }; } exports["default"] = storage;