import { combineEpics, ofType } from 'redux-observable'; import { ENTERED_FORECAST_PAGE } from 'app/common/store/router/router.constants'; import { marketFetchCommentariesFailure, marketFetchCommentariesRequest, marketFetchCommentariesSuccess, marketFetchExposureFailure, marketFetchExposureRequest, marketFetchExposureSuccess, resetMarketsCommentariesLimit, setMarkets, setMarketsCommentaries, setMarketsCommentariesLimit, setMarketsExposure, } from 'app/modules/markets/store/markets.actions'; import { MARKETS } from 'app/modules/markets/store/markets.constants'; import { catchError, map, switchMap } from 'rxjs/operators'; import { PretypedEpic } from 'app/common/store/store.types'; const enteredForecastPageEpic: PretypedEpic<{ pool: number }> = (action$) => { return action$.pipe( ofType(ENTERED_FORECAST_PAGE), map((action) => [ marketFetchCommentariesRequest(action.payload.pool), marketFetchExposureRequest(action.payload.pool), ]) ); }; const fetchMarketExposureEpic: PretypedEpic = (action$, _, { marketsService }) => { return action$.pipe( ofType(MARKETS.FETCH_EXPOSURE_REQUEST), switchMap((action) => marketsService.getMarkets(action.payload).pipe( map((markets) => { const forecastExposure = markets.filter((market) => (market.showExposures)).map((market) => { return { poolPercentage: market.poolPercentage, marketPercentage: market.marketPercentage, imoCargo: market.imoCargo || null, market: { id: market.id, name: market.name, }, }; }); return [ setMarketsExposure(forecastExposure), marketFetchExposureSuccess(), setMarkets(markets), ]; }), catchError((error: unknown) => [ marketFetchExposureFailure(error), ]) )), ); }; const marketFetchCommentariesEpic: PretypedEpic = (action$, _, { marketsService }) => { return action$.pipe( ofType(MARKETS.FETCH_COMMENTARIES_REQUEST), switchMap((action) => marketsService.getPoolComments(action.payload).pipe( map((marketCommentaries) => [ setMarketsCommentaries(marketCommentaries), resetMarketsCommentariesLimit(), marketFetchCommentariesSuccess(), ]), catchError((error) => [ marketFetchCommentariesFailure(error), ]), )), ); }; const increaseMarketCommentariesLimit: PretypedEpic = (action$, store) => { return action$.pipe( ofType(MARKETS.INCREASE_COMMENTARIES_LIMIT), map(() => setMarketsCommentariesLimit(store.value.markets.limit + MARKETS.COMMENTARIES_LIMIT)) ); }; export const marketsEpics = combineEpics( enteredForecastPageEpic, fetchMarketExposureEpic, marketFetchCommentariesEpic, increaseMarketCommentariesLimit, );