All files / date-picker middleware.js

84.85% Statements 28/33
68.18% Branches 15/22
100% Functions 5/5
84.38% Lines 27/32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72        2x 1x 1x 1x   1x   2x 1x 1x 1x   1x     5x     5x 5x 5x       2x           1x         1x 1x                       1x 1x 1x 1x   1x   1x           1x   1x   3x    
import { actions, actionTypes } from '@bufferapp/async-data-fetch';
import { actionTypes as profileActionTypes } from '@bufferapp/analyze-profile-selector';
import { actions as dateActions, actionTypes as dateActionTypes } from './reducer';
 
const getStartDate = (query) => {
  let startDate = query.match(/start_date=(.*)&/);
  Eif (startDate) {
    startDate = parseInt(startDate[1], 10);
  }
  return startDate;
};
const getEndDate = (query) => {
  let endDate = query.match(/end_date=(.*)$/);
  Eif (endDate) {
    endDate = parseInt(endDate[1], 10);
  }
  return endDate;
};
 
export default ({ dispatch, getState }) => next => (action) => {
  let startDate;
  let endDate;
  const state = getState();
  const result = action.result;
  switch (action.type) {
    case dateActionTypes.SET_DATE_RANGE:
      // we don't want to trigger the event if the date is unchanged
      // this is useful to prevent fetching the same data muliple times
      if (
        action.startDate === state.date.startDate &&
        action.endDate === state.date.endDate &&
        // needed because we are changing start and end date with the custom picker open
        !state.date.calendarOpen
      ) {
        return null;
      }
 
      // We don't want dispatch SET_DATE_RANGE event if we are missing profiles
      // or it will result in malformed requests
      Eif (state.profileLoader.loading) {
        return null;
      }
 
      break;
    case `get_report_${actionTypes.FETCH_SUCCESS}`:
      if (result.date_range.range) {
        dispatch(dateActions.setDatePreset(result.date_range));
      } else {
        dispatch(dateActions.setDateRange(result.date_range.startDate, result.date_range.endDate));
      }
      break;
    case `user_${actionTypes.FETCH_SUCCESS}`:
      startDate = getStartDate(state.router.location.search);
      endDate = getEndDate(state.router.location.search);
      Eif (startDate && endDate) {
        dispatch(dateActions.setDateRange(startDate, endDate));
      }
      break;
    case profileActionTypes.SELECT_PROFILE:
      dispatch(actions.fetch({
        name: 'analytics_start_date',
        args: {
          profileId: action.profile.id,
        },
      }));
      break;
    default:
      break;
  }
  return next(action);
};