Skip to content

Instantly share code, notes, and snippets.

@srounce
Forked from jamieallen59/rx.js
Last active February 24, 2017 11:57
Show Gist options
  • Save srounce/cc3f9dfaec6ddd88351b81051b0cab77 to your computer and use it in GitHub Desktop.
Save srounce/cc3f9dfaec6ddd88351b81051b0cab77 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/mergeMap';
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);
const requestPostcode = getRequestPostcode(validLinkedAccounts);
if (!requestPostcode) {
// return an action here? (Correct! see below)
return of(noLinkedAccounts((['No suitable linked energy accounts']));
}
const requestObject = { postcode: requestPostcode };
const fetchObject = getAuthenticatedFetchObject(ENERGY_INITIAL_COMPARISON_URL, 'POST', requestObject);
const fetch$ = fromPromise(callFetch(fetchObject))
.mergeMap(response => {
const { average_savings: averageSavings } = response;
if (averageSavings) {
return of(
getPreSwitchComparisonSuccess(),
showInitialEnergySavings(),
updateAverageSavings(averageSavings)
);
}
return null; // Should be mapping to some action or throwing error and going to `catch(error)` if `averageSavings` doesn't exist
})
.catch(error => {
return of(
getPreSwitchComparisonFailure(error),
hideInitialEnergySavings()
);
});
return of(
updatePreSwitchFormAccount(validLinkedAccounts),
updateAverageSavingsPostcode(requestPostcode)
).concat(fetch$)
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment