Completed
Push — master ( 2f8415...e6e0b0 )
by Rain
02:22
created

dev/Common/ClientStorageDriver/LocalStorage.js   A

Size

Lines of Code 74

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
nc 1
dl 0
loc 74
rs 10
noi 0
1
2
import window from 'window';
3
import {isUnd} from 'Common/Utils';
4
import {isStorageSupported} from 'Storage/RainLoop';
5
import {CLIENT_SIDE_STORAGE_INDEX_NAME} from 'Common/Consts';
6
7
class LocalStorageDriver
8
{
9
	s = null;
10
11
	constructor() {
12
		this.s = window.localStorage || null;
13
	}
14
15
	/**
16
	 * @param {string} key
17
	 * @param {*} data
18
	 * @returns {boolean}
19
	 */
20
	set(key, data) {
21
		if (!this.s)
22
		{
23
			return false;
24
		}
25
26
		let storageResult = null;
27
		try
28
		{
29
			const storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null;
30
			storageResult = null === storageValue ? null : window.JSON.parse(storageValue);
31
		}
32
		catch (e) {} // eslint-disable-line no-empty
33
34
		(storageResult || (storageResult = {}))[key] = data;
35
36
		try
37
		{
38
			this.s.setItem(CLIENT_SIDE_STORAGE_INDEX_NAME, window.JSON.stringify(storageResult));
39
			return true;
40
		}
41
		catch (e) {} // eslint-disable-line no-empty
42
43
		return false;
44
	}
45
46
	/**
47
	 * @param {string} key
48
	 * @returns {*}
49
	 */
50
	get(key) {
51
		if (!this.s)
52
		{
53
			return null;
54
		}
55
56
		try
57
		{
58
			const
59
				storageValue = this.s.getItem(CLIENT_SIDE_STORAGE_INDEX_NAME) || null,
60
				storageResult = null === storageValue ? null : window.JSON.parse(storageValue);
61
62
			return (storageResult && !isUnd(storageResult[key])) ? storageResult[key] : null;
63
		}
64
		catch (e) {} // eslint-disable-line no-empty
65
66
		return null;
67
	}
68
69
	/**
70
	 * @returns {boolean}
71
	 */
72
	static supported() {
73
		return isStorageSupported('localStorage');
74
	}
75
}
76
77
export {LocalStorageDriver, LocalStorageDriver as default};
78