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

51 lines
1.1 KiB
JavaScript
Raw Normal View History

2016-02-25 18:30:10 -08:00
import { Observable } from 'rx';
import { normalize, Schema, arrayOf } from 'normalizr';
2016-02-05 20:48:59 -08:00
2016-02-25 18:30:10 -08:00
import { fetchJobsCompleted } from './actions';
import { fetchJobs } from './types';
import { handleError } from '../../../redux/types';
const job = new Schema('job', { idAttribute: 'id' });
export default ({ services }) => ({ dispatch }) => next => {
2016-02-05 20:48:59 -08:00
return function fetchJobsSaga(action) {
2016-02-25 18:30:10 -08:00
if (action.type !== fetchJobs) {
return next(action);
}
const { payload: id } = action;
const data = { service: 'jobs' };
if (id) {
2016-02-29 17:04:45 -08:00
data.params = { id };
2016-02-25 18:30:10 -08:00
}
return services.readService$(data)
.map(jobs => {
if (!Array.isArray(jobs)) {
jobs = [jobs];
}
const { entities, result } = normalize(
{ jobs },
{ jobs: arrayOf(job) }
);
return fetchJobsCompleted(
result.jobs[0],
{
2016-02-28 17:00:31 -08:00
entities: entities.job,
2016-02-25 18:30:10 -08:00
results: result.jobs
}
);
})
.catch(error => {
return Observable.just({
type: handleError,
error
});
})
.doOnNext(dispatch);
2016-02-05 20:48:59 -08:00
};
};