@aller/blink
Version:
A library for tracking user behaviour.
43 lines (37 loc) • 1.28 kB
text/typescript
import {
ARTICLE_PREVIEW_SCREEN_ENTER,
PAGE_INIT,
CLICK,
ARTICLE_PREVIEW_SCREEN_EXIT,
} from './actions';
import getInscreenTime from './selectors/get-inscreen-time';
import getPageState from './selectors/get-page-state';
export default function persistenceMiddleware(
persistState: (key: string, value: any) => any,
) {
return ({ getState }: { getState: any }) => (next: any) => (action: any) => {
// Execute the action, which might mutate the state
const returnValue = next(action);
const page = getPageState(getState(), action.payload.pageId);
switch (action.type) {
case PAGE_INIT:
persistState(`${page.id}::pageView`, page.state.general.pageView);
break;
case CLICK:
persistState(`${page.id}::clicked::${action.payload.id}`, true);
break;
case ARTICLE_PREVIEW_SCREEN_ENTER:
case ARTICLE_PREVIEW_SCREEN_EXIT:
if (action.payload.url !== page.state.general.url) {
const id = action.payload.id;
const ap = page.state.articlePreview[id] || {};
persistState(`${page.id}::impression::${id}`, {
...ap,
inscreenTime: getInscreenTime(page.state, id, new Date()),
});
}
break;
}
return returnValue;
};
}