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

82 lines
2.4 KiB
JavaScript
Raw Normal View History

import { Observable } from 'rx';
import debug from 'debug';
import { challengeSelector } from './selectors';
import types from './types';
2016-06-09 16:02:51 -07:00
import {
fetchChallengeCompleted,
fetchChallengesCompleted,
2016-06-21 16:28:13 -07:00
updateCurrentChallenge,
initMap
} from './actions';
import {
createMapUi,
filterComingSoonBetaFromEntities
} from '../utils';
2016-06-21 16:28:13 -07:00
import {
delayedRedirect,
createErrorObservable
2016-06-21 16:28:13 -07:00
} from '../../../redux/actions';
import createNameIdMap from '../../../../utils/create-name-id-map';
2016-03-21 15:39:45 -07:00
const isDev = debug.enabled('fcc:*');
const { fetchChallenge, fetchChallenges, replaceChallenge } = types;
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();
const lang = state.app.lang;
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)
.retry(3)
2016-06-09 16:02:51 -07:00
.flatMap(({ entities, result, redirect } = {}) => {
if (type === fetchChallenge) {
return Observable.of(
fetchChallengeCompleted(
createNameIdMap(entities),
result
),
2016-06-09 16:02:51 -07:00
updateCurrentChallenge(entities.challenge[result.challenge]),
redirect ? delayedRedirect(redirect) : null
);
}
const filteredEntities = filterComingSoonBetaFromEntities(
entities,
isDev
);
2016-06-21 16:28:13 -07:00
return Observable.of(
fetchChallengesCompleted(
createNameIdMap(filteredEntities),
result
2016-06-21 16:28:13 -07:00
),
initMap(createMapUi(filteredEntities, result)),
);
2016-04-24 21:54:48 -07:00
})
.catch(createErrorObservable);
2016-04-24 21:54:48 -07:00
});
}