snappymail/dev/Common/ClientStorageDriver/Cookie.jsx

73 lines
1.3 KiB
React
Raw Normal View History

2015-11-15 08:23:16 +08:00
2016-07-02 06:49:59 +08:00
import window from 'window';
import $ from '$';
import JSON from 'JSON';
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 CookieDriver
{
/**
* @param {string} key
* @param {*} data
2016-06-30 08:02:45 +08:00
* @returns {boolean}
2015-11-15 08:23:16 +08:00
*/
set(key, data) {
let
2015-11-15 08:23:16 +08:00
result = false,
2016-06-30 08:02:45 +08:00
storageResult = null;
2015-11-15 08:23:16 +08:00
try
{
const storageValue = $.cookie(CLIENT_SIDE_STORAGE_INDEX_NAME);
storageResult = null === storageValue ? null : JSON.parse(storageValue);
}
2016-07-02 06:49:59 +08:00
catch (e) {} // eslint-disable-line no-empty
2015-11-15 08:23:16 +08:00
(storageResult || (storageResult = {}))[key] = data;
try
{
$.cookie(CLIENT_SIDE_STORAGE_INDEX_NAME, JSON.stringify(storageResult), {
2016-04-21 01:12:51 +08:00
expires: 30
2015-11-15 08:23:16 +08:00
});
result = true;
}
2016-07-02 06:49:59 +08:00
catch (e) {} // eslint-disable-line no-empty
2015-11-15 08:23:16 +08:00
return result;
}
/**
* @param {string} key
2016-06-30 08:02:45 +08:00
* @returns {*}
2015-11-15 08:23:16 +08:00
*/
2016-04-21 01:12:51 +08:00
get(key) {
2015-11-15 08:23:16 +08:00
let result = null;
2015-11-15 08:23:16 +08:00
try
{
const
2015-11-15 08:23:16 +08:00
storageValue = $.cookie(CLIENT_SIDE_STORAGE_INDEX_NAME),
2016-06-30 08:02:45 +08:00
storageResult = null === storageValue ? null : JSON.parse(storageValue);
2015-11-15 08:23:16 +08:00
2016-06-07 05:57:52 +08:00
result = (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null;
2015-11-15 08:23:16 +08:00
}
2016-07-02 06:49:59 +08:00
catch (e) {} // eslint-disable-line no-empty
2015-11-15 08:23:16 +08:00
2016-04-21 01:12:51 +08:00
return result;
}
2015-11-15 08:23:16 +08:00
/**
2016-06-30 08:02:45 +08:00
* @returns {boolean}
2015-11-15 08:23:16 +08:00
*/
static supported() {
return !!(window.navigator && window.navigator.cookieEnabled);
}
}
export {CookieDriver, CookieDriver as default};