Files
freeCodeCamp/common/app/routes/challenges/redux/fetch-challenges-saga.js
2016-07-28 23:39:17 -07:00

58 lines
1.8 KiB
JavaScript

import { Observable } from 'rx';
import { challengeSelector } from './selectors';
import {
fetchChallenge,
fetchChallenges,
replaceChallenge
} from './types';
import {
delayedRedirect,
createErrorObserable
} from '../../../redux/actions';
import {
fetchChallengeCompleted,
fetchChallengesCompleted,
updateCurrentChallenge
} from './actions';
export default function fetchChallengesSaga(action$, getState, { services }) {
return action$
.filter(({ type }) => (
type === fetchChallenges ||
type === fetchChallenge ||
type === replaceChallenge
))
.flatMap(({ type, payload: { dashedName, block } = {} }) => {
const state = getState();
if (type === replaceChallenge) {
const { challenge: newChallenge } = challengeSelector({
...state,
challengesApp: {
...state.challengesApp,
challenge: dashedName
}
});
if (state.challengesApp.challenge !== newChallenge.dashedName) {
return Observable.just(updateCurrentChallenge(newChallenge));
}
return Observable.just(null);
}
const options = { service: 'map' };
if (type === fetchChallenge) {
options.params = { dashedName, block };
}
return services.readService$(options)
.flatMap(({ entities, result, redirect } = {}) => {
if (type === fetchChallenge) {
return Observable.of(
fetchChallengeCompleted(entities, result),
updateCurrentChallenge(entities.challenge[result.challenge]),
redirect ? delayedRedirect(redirect) : null
);
}
return Observable.just(fetchChallengesCompleted(entities, result));
})
.catch(createErrorObserable);
});
}