2018-01-29 22:20:38 +00:00
|
|
|
// @flow
|
|
|
|
|
2017-12-14 17:02:32 +00:00
|
|
|
import _ from 'lodash';
|
|
|
|
|
2018-02-02 19:35:49 +00:00
|
|
|
import { MiddlewareRegistry, toState } from '../redux';
|
|
|
|
|
|
|
|
import PersistenceRegistry from './PersistenceRegistry';
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
/**
|
2018-02-02 19:35:49 +00:00
|
|
|
* The delay in milliseconds that passes between the last state change and the
|
|
|
|
* persisting of that state in the storage.
|
2017-12-14 17:02:32 +00:00
|
|
|
*/
|
2018-01-29 22:20:38 +00:00
|
|
|
const PERSIST_STATE_DELAY = 2000;
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A throttled function to avoid repetitive state persisting.
|
|
|
|
*/
|
2018-01-29 22:20:38 +00:00
|
|
|
const throttledPersistState
|
|
|
|
= _.throttle(
|
2018-02-02 19:35:49 +00:00
|
|
|
state => PersistenceRegistry.persistState(state),
|
2018-01-29 22:20:38 +00:00
|
|
|
PERSIST_STATE_DELAY);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
2018-08-01 20:37:15 +00:00
|
|
|
// Web only code.
|
|
|
|
// We need the <tt>if</tt> beacuse it appears that on mobile the polyfill is not
|
|
|
|
// executed yet.
|
|
|
|
if (typeof window.addEventListener === 'function') {
|
|
|
|
window.addEventListener('unload', () => {
|
|
|
|
throttledPersistState.flush();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-12-14 17:02:32 +00:00
|
|
|
/**
|
|
|
|
* A master MiddleWare to selectively persist state. Please use the
|
2018-02-02 19:35:49 +00:00
|
|
|
* {@link persisterconfig.json} to set which subtrees of the redux state should
|
2018-01-29 22:20:38 +00:00
|
|
|
* be persisted.
|
2017-12-14 17:02:32 +00:00
|
|
|
*
|
|
|
|
* @param {Store} store - The redux store.
|
|
|
|
* @returns {Function}
|
|
|
|
*/
|
|
|
|
MiddlewareRegistry.register(store => next => action => {
|
2018-02-02 19:35:49 +00:00
|
|
|
const oldState = toState(store);
|
2017-12-14 17:02:32 +00:00
|
|
|
const result = next(action);
|
2018-02-02 19:35:49 +00:00
|
|
|
const newState = toState(store);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
2018-02-02 19:35:49 +00:00
|
|
|
oldState === newState || throttledPersistState(newState);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
return result;
|
|
|
|
});
|