reducers.ts 1.58 KB
import { sortBy, unionBy, get, set } from 'lodash/fp';
import { createReducer } from '../../helpers/Reducer';
import {fetchThreadContents as fetchThreadContentsRoutine, postThreadContent} from './middlewares/thread-contents/routines';
import {ThreadContentsState} from '../../definitions/portal-interfaces';
import ThreadContent from '../../models/ThreadContent';

const initialState = {
  collection: [],
  meta: null,
  isFetching: false,
  isFetched: false
};

const fetchThreadContentsHandler = () => ({
  [fetchThreadContentsRoutine.REQUEST]: (state: ThreadContentsState) => ({
    ...state,
    isFetching: true,
    isFetched: false
  }),
  [fetchThreadContentsRoutine.SUCCESS]: (
    state: ThreadContentsState,
    {payload: {collection, meta}}: {payload: ThreadContentsState}) => {
    const newCollection = unionBy((each: ThreadContent) => get('id', each), collection, state.collection);
    const orderedCollection = sortBy('createdAt', newCollection);
    return {
      ...state,
      collection: orderedCollection,
      meta,
      isFetching: false,
      isFetched: true
    };
  },
  [fetchThreadContentsRoutine.FAILURE]: (state: ThreadContentsState) => ({
    ...state,
    isFetching: false,
    isFetched: true
  })
});

const postThreadContentHandler = () => ({
  [postThreadContent.SUCCESS]: (
    state: ThreadContentsState,
    { payload: threadContent }: { payload: ThreadContent }) => {
    return set('collection', [...state.collection, threadContent], state);
  }
});

export default createReducer(initialState, {
  ...fetchThreadContentsHandler(),
  ...postThreadContentHandler()
});