Files
freeCodeCamp/common/app/routes/challenges/redux/fetch-challenges-saga.js

61 lines
1.9 KiB
JavaScript
Raw Normal View History

import { Observable } from 'rx';
import { challengeSelector } from './selectors';
import {
fetchChallenge,
fetchChallenges,
replaceChallenge
} from './types';
import {
2016-06-09 16:02:51 -07:00
delayedRedirect,
createErrorObserable
} from '../../../redux/actions';
import {
fetchChallengeCompleted,
fetchChallengesCompleted,
updateCurrentChallenge
} from './actions';
2016-03-21 15:39:45 -07:00
2016-04-24 21:54:48 -07:00
export default function fetchChallengesSaga(action$, getState, { services }) {
return action$
2016-06-01 15:52:08 -07:00
.filter(({ type }) => (
type === fetchChallenges ||
type === fetchChallenge ||
type === replaceChallenge
2016-06-01 15:52:08 -07:00
))
2016-06-09 16:02:51 -07:00
.flatMap(({ type, payload: { dashedName, block } = {} }) => {
const state = getState();
2016-06-17 12:35:10 -07:00
const lang = state.app.languageTag;
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' };
2016-06-17 12:35:10 -07:00
options.params = { lang };
if (type === fetchChallenge) {
2016-06-17 12:35:10 -07:00
options.params.dashedName = dashedName;
options.params.block = block;
}
return services.readService$(options)
2016-06-09 16:02:51 -07:00
.flatMap(({ entities, result, redirect } = {}) => {
if (type === fetchChallenge) {
return Observable.of(
fetchChallengeCompleted(entities, result),
2016-06-09 16:02:51 -07:00
updateCurrentChallenge(entities.challenge[result.challenge]),
redirect ? delayedRedirect(redirect) : null
);
}
return Observable.just(fetchChallengesCompleted(entities, result));
2016-04-24 21:54:48 -07:00
})
2016-05-06 16:04:23 -07:00
.catch(createErrorObserable);
2016-04-24 21:54:48 -07:00
});
}