Skip to content

Commit

Permalink
Merge pull request #2 from bharatpe/storage-util
Browse files Browse the repository at this point in the history
Storage Utils added
  • Loading branch information
krishpe authored Jun 29, 2020
2 parents bd62520 + 96e3e2a commit a1c35e6
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
2 changes: 1 addition & 1 deletion dist/lib.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

81 changes: 81 additions & 0 deletions src/StorageUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* @name StorageMap object used for when Local Storage quota exceeded
*/
let StorageMap = {};

/**
* @function strToJson
* @param {string} str
* @description string to JSON object conversation
*/
const strToJson = (str) => {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}

/**
* @function _get
* @param {string} key
* @description get value from localstorage by key name
*/
const _get = (key) => {
let value = StorageMap[key] || window.localStorage.getItem(key);
value = strToJson(value);
return value;
}

/**
* @function _set
* @param {string} key
* @param {string} value
* @description set value to localstorage
*/
const _set = (key, value) => {
if (typeof value === 'object') {
value = JSON.stringify(value);
}
try {
window.localStorage.setItem(key, value);
} catch (e) {
StorageMap[key] = value;
}
}

/**
* @function _has
* @param {string} key
* @description check key available in localstorage
*/
const _has = (key) => {
return (StorageMap.hasOwnProperty(key) || window.localStorage.getItem(key) !== null);
}

/**
* @function _remove
* @param {string} key
* @description remove key from localstorage
*/
const _remove = (key) => {
window.localStorage.removeItem(key);
delete StorageMap[key];
}

/**
* @function _removeAll
* @description remove all items from localstorage
*/
const _removeAll = () => {
StorageMap = {};
window.localStorage.clear();
}

export default {
get: _get,
set: _set,
has: _has,
remove: _remove,
removeAll: _removeAll
};

0 comments on commit a1c35e6

Please sign in to comment.