PromucFlow_constructor/app/client/src/sagas/BatchSagas.tsx

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-04-13 08:24:13 +00:00
/* eslint-disable @typescript-eslint/ban-ts-ignore */
2020-04-17 16:15:09 +00:00
import _ from "lodash";
import { put, debounce, takeEvery, all } from "redux-saga/effects";
2020-04-13 08:24:13 +00:00
import { ReduxAction, ReduxActionTypes } from "constants/ReduxActionConstants";
2020-04-17 16:15:09 +00:00
const BATCH_PRIORITY = {
[ReduxActionTypes.SET_META_PROP]: {
priority: 0,
needsSaga: false,
},
[ReduxActionTypes.RESET_WIDGET_META]: {
priority: 0,
needsSaga: false,
},
[ReduxActionTypes.UPDATE_WIDGET_PROPERTY]: {
priority: 0,
needsSaga: false,
},
[ReduxActionTypes.EXECUTE_ACTION]: {
priority: 1,
needsSaga: true,
},
[ReduxActionTypes.EXECUTE_PAGE_LOAD_ACTIONS]: {
priority: 1,
needsSaga: true,
},
[ReduxActionTypes.UPDATE_ACTION_PROPERTY]: {
2020-07-28 10:41:51 +00:00
priority: 0,
needsSaga: false,
},
2020-07-28 10:41:51 +00:00
[ReduxActionTypes.UPDATE_ACTION_INIT]: {
priority: 1,
needsSaga: true,
},
2020-04-17 16:15:09 +00:00
};
const batches: ReduxAction<any>[][] = [];
2020-04-13 08:24:13 +00:00
function* storeUpdatesSaga(action: ReduxAction<ReduxAction<any>>) {
2020-04-17 16:15:09 +00:00
try {
const priority = BATCH_PRIORITY[action.payload.type].priority;
const currentPriorityBatch = batches[priority] || [];
currentPriorityBatch.push(action.payload);
_.set(batches, `[${priority}]`, currentPriorityBatch);
yield put({ type: ReduxActionTypes.EXECUTE_BATCH });
} catch (e) {
console.error(`${action.payload.type} action priority not set`);
}
2020-04-13 08:24:13 +00:00
}
function* executeBatchSaga() {
2020-04-17 16:15:09 +00:00
for (let priority = 0; priority < batches.length; priority++) {
const batch = batches[priority];
if (Array.isArray(batch) && batch.length) {
const needsSaga = batch.filter(b => BATCH_PRIORITY[b.type].needsSaga);
const canBatch = batch.filter(b => !BATCH_PRIORITY[b.type].needsSaga);
batches[priority] = [];
// @ts-ignore
yield put(canBatch);
if (needsSaga.length) {
for (const sagaAction of needsSaga) {
yield put(sagaAction);
}
}
}
}
2020-04-13 08:24:13 +00:00
}
export default function* root() {
2020-04-17 16:15:09 +00:00
yield all([
debounce(20, ReduxActionTypes.EXECUTE_BATCH, executeBatchSaga),
takeEvery(ReduxActionTypes.BATCHED_UPDATE, storeUpdatesSaga),
]);
2020-04-13 08:24:13 +00:00
}