-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from bharatpe/storage-util
Storage Utils added
- Loading branch information
Showing
2 changed files
with
82 additions
and
1 deletion.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}; |