snappymail/dev/Common/ClientStorageDriver/LocalStorage.jsx

79 lines
1.4 KiB
React
Raw Normal View History

2015-11-15 08:23:16 +08:00
import {window, JSON} from 'common';
2016-06-07 05:57:52 +08:00
import {isUnd} from 'Common/Utils';
2015-11-15 08:23:16 +08:00
import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts';
class LocalStorageDriver
{
/**
* @param {string} key
* @param {*} data
* @return {boolean}
*/
set(key, data) {
let
result = false,
storageResult = null
;
try
{
const storageValue = window.localStorage[CLIENT_SIDE_STORAGE_INDEX_NAME] || null;
storageResult = null === storageValue ? null : JSON.parse(storageValue);
}
2016-04-21 01:12:51 +08:00
catch (e)
{
// eslint-disable-line no-empty
}
2015-11-15 08:23:16 +08:00
(storageResult || (storageResult = {}))[key] = data;
try
{
window.localStorage[CLIENT_SIDE_STORAGE_INDEX_NAME] = JSON.stringify(storageResult);
result = true;
}
2016-04-21 01:12:51 +08:00
catch (e)
{
// eslint-disable-line no-empty
}
2015-11-15 08:23:16 +08:00
return result;
}
/**
* @param {string} key
* @return {*}
*/
get(key) {
2016-04-21 01:12:51 +08:00
2015-11-15 08:23:16 +08:00
let result = null;
2016-04-21 01:12:51 +08:00
2015-11-15 08:23:16 +08:00
try
{
2016-04-21 01:12:51 +08:00
const
2015-11-15 08:23:16 +08:00
storageValue = window.localStorage[CLIENT_SIDE_STORAGE_INDEX_NAME] || null,
storageResult = null === storageValue ? null : JSON.parse(storageValue)
;
2016-06-07 05:57:52 +08:00
result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null;
2016-04-21 01:12:51 +08:00
}
catch (e)
{
// eslint-disable-line no-empty
2015-11-15 08:23:16 +08:00
}
return result;
}
/**
* @return {boolean}
*/
static supported() {
return !!window.localStorage;
}
}
export {LocalStorageDriver, LocalStorageDriver as default};