Skip to content

Instantly share code, notes, and snippets.

@thenickcox
Created April 11, 2017 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thenickcox/55941aa6093101d25205b995a306559a to your computer and use it in GitHub Desktop.
Save thenickcox/55941aa6093101d25205b995a306559a to your computer and use it in GitHub Desktop.
export const RESULTS_POLLING = 'RESULTS_POLLING';
const setPolling = val => ({ type: RESULTS_POLLING, pollingType: val });
export const SET_POLLING_DURATION = 'SET_POLLING_DURATION';
const setPollingDuration = (val, count, dates) => (
{ type: SET_POLLING_DURATION, duration: val, count, dates }
);
export const INCREMENT_POLL_COUNT = 'INCREMENT_POLL_COUNT';
const incrementPollCount = () => ({ type: INCREMENT_POLL_COUNT });
export const initiatePolling = data => (
(dispatch, getState) => {
const state = getState();
const pollCount = state.results.polling.pollCount;
if (pollCount === 0) dispatch(setPolling('indeterminate'));
const { REPORTS_SUMMARY_URL } = config;
fetch(`${REPORTS_SUMMARY_URL}/${data.temporary_id}`, { credentials: 'include' })
.then((response) => {
// if (!response.ok) throw Error(response.statusText);
const statusPromise = Promise.resolve(response.status);
return Promise.all([response.json(), statusPromise]);
})
.then((promises) => {
const [d, status] = promises;
if (status === 200) {
dispatch(incrementPollCount());
dispatch(setPolling(null));
return dispatch(processResults(d));
}
if (pollCount === 0) {
dispatch(setPollingDuration(d.predicted_wait_time, d.time_entry_count, d.dates));
}
dispatch(incrementPollCount());
const timeout = (d.predicted_wait_time * 1000) / 5;
return setTimeout(() => { dispatch(initiatePolling(d)); }, Math.max(timeout, 1));
});
}
);
// ...
export const fetchSummaryRows = () => (
(dispatch, getState) => {
const { REPORTS_SUMMARY_URL } = config;
dispatch({ type: REQUEST_RESULTS });
const payload = buildPayload(getState());
payload.today = getCurrentUnixDate();
return fetch(REPORTS_SUMMARY_URL, {
credentials: 'include',
method: 'POST',
headers: {
// eslint-disable-next-line
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then((response) => {
// if (!response.ok) throw Error(response.statusText);
const statusPromise = Promise.resolve(response.status);
return Promise.all([response.json(), statusPromise]);
})
.then((promises) => {
const [data, status] = promises;
if (status === 202) {
return dispatch(initiatePolling(data));
}
return dispatch(processResults(data));
});
// .catch(() => dispatch(toggleErrorState()));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment