-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
86 lines (73 loc) · 2.59 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const { createTransform } = require('redux-persist');
/**
* Transforms state on its way to being serialized and persisted
* @param inboundState
* @param config
* @return {*}
*/
const transformPersistence = (inboundState, config) => {
inboundState = inboundState || {};
// If autoExpire is required i.e. user won't be setting the time
// then on each update change the `persistedAt` to be current time
// so that the rehydrater will pick it up based on this time if
// the record is not updated for some time
if (config.autoExpire && !inboundState[config.persistedAtKey]) {
inboundState = Object.assign({}, inboundState, {
[config.persistedAtKey]: (new Date()).getTime()
});
}
return inboundState;
};
/**
* Transform state being rehydrated
* @param outboundState
* @param config
* @return {*}
*/
const transformRehydrate = (outboundState, config) => {
outboundState = outboundState || {};
// Check for the possible expiry if state has the persisted date
if (config.expireSeconds && outboundState[config.persistedAtKey]) {
const startTime = (new Date(outboundState[config.persistedAtKey])).getTime();
const endTime = (new Date()).getTime();
const duration = endTime - startTime;
const seconds = duration / 1000;
// If the state is older than the set expiry time,
// reset it to initial state
if (seconds > config.expireSeconds) {
return Object.assign({}, config.expiredState);
}
}
return outboundState;
};
/**
* Creates transform object with the given expiry configuration
* @param reducerKey
* @param config
* @return {Transform<{}, any>}
*/
function expireReducer(reducerKey, config = {}) {
const defaults = {
// Key to be used for the time relative to which store is to be expired
persistedAtKey: '__persisted_at',
// Seconds after which store will be expired
expireSeconds: null,
// State to be used for resetting e.g. provide initial reducer state
expiredState: {},
// Use it if you don't want to manually set the time and want the store to
// be automatically expired if the record is not updated in the `expireSeconds` time
autoExpire: false
};
config = Object.assign({}, defaults, config);
return createTransform(
// transform state on its way to being serialized and persisted.
(inboundState) => transformPersistence(inboundState, config),
// transform state being rehydrated
(outboundState) => transformRehydrate(outboundState, config),
// define which reducers this transform gets called for.
{
whitelist: [reducerKey]
}
);
}
module.exports = expireReducer;