Skip to content

Instantly share code, notes, and snippets.

@jamieallen59
Created February 24, 2017 11:37
Show Gist options
  • Save jamieallen59/b06c9a303613a6e1fb7eaf04ebb488df to your computer and use it in GitHub Desktop.
Save jamieallen59/b06c9a303613a6e1fb7eaf04ebb488df to your computer and use it in GitHub Desktop.
import { fromPromise } from 'rxjs/observable/fromPromise';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
// IGNORE (just filters)
const isValidLinkedAccount = linkedAccount => {
const { is_linked: isLinked, link_failed: linkFailed, status, service_status: serviceStatus } = linkedAccount;
return isLinked && !linkFailed && status === 'active' && serviceStatus === 'active';
};
const hasRequiredEnergyLinxFields = linkedAccount => {
const { postcode, provider_code: providerCode, provider_label: providerLabel, tariff_name: tariffName } = linkedAccount;
return postcode && providerCode && providerLabel && tariffName;
};
/--------------------------
export const getPreSwitchComparisonEpic = (action$, store) => (
action$
.ofType(GET_PRE_SWITCH_COMPARISON_ATTEMPT)
.switchMap(action => {
// Apparently it's not recommended to dispatch from within an epic, but needed here
// to help work with existing code
const { dispatch } = store;
const { linkedAccounts } = action;
const validLinkedAccounts = linkedAccounts
.filter(isValidLinkedAccount)
.filter(hasRequiredEnergyLinxFields);
dispatch(updatePreSwitchFormAccount(validLinkedAccounts));
const requestPostcode = getRequestPostcode(validLinkedAccounts);
dispatch(updateAverageSavingsPostcode(requestPostcode));
if (!requestPostcode) {
// return an action here?
// return reject(['No suitable linked energy accounts']);
}
const requestObject = { postcode: requestPostcode };
const fetchObject = getAuthenticatedFetchObject(ENERGY_INITIAL_COMPARISON_URL, 'POST', requestObject);
return fromPromise(callFetch(fetchObject))
.map(response => {
const { average_savings: averageSavings } = response;
if (averageSavings) {
dispatch(getPreSwitchComparisonSuccess());
dispatch(showInitialEnergySavings());
return dispatch(updateAverageSavings(averageSavings));
}
return false;
})
.catch(error => {
dispatch(hideInitialEnergySavings());
return dispatch(getPreSwitchComparisonFailure(error));
});
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment