-
Notifications
You must be signed in to change notification settings - Fork 16
/
getStateFromCookies.js
52 lines (48 loc) · 1.41 KB
/
getStateFromCookies.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import merge from 'lodash/merge';
import { getCookie as getBrowserCookie } from './cookieApi';
/**
* safely get cookies
* @param {Function} getCookie
* @param {String} cookieName
* @return {any} cookieValue
*/
const safeGetCookie = (getCookie, cookieName) => {
try {
return JSON.parse(getCookie(cookieName));
} catch (_) {
return getCookie(cookieName);
}
};
/**
* get State Object from Path String
* @param {String} path
* @param {any} valueFromCookie
* @return {Object} new state
*/
const getStateFromPath = (path, valueFromCookie) => {
const pathSplit = path.split('.');
return pathSplit.reverse()
.reduce((finalPathState, currPathKey) =>
({ [currPathKey]: finalPathState }), valueFromCookie);
};
/**
* read browser cookie into state
* @param {Object} preloaded state
* @param {Object} paths
* @param {Object} get Cookie implementation
* @return {Object} new state
*/
const getStateFromCookies = (
preloadedState = {},
paths,
getCookie = getBrowserCookie
) => {
const pathStates = Object.keys(paths).map((path) => {
const pathConfig = paths[path];
const valueFromCookie = safeGetCookie(getCookie, pathConfig.name);
return getStateFromPath(path, valueFromCookie);
});
return pathStates
.reduce((finalState, pathState) => (merge({}, finalState, pathState)), preloadedState);
};
export default getStateFromCookies;