static-cms/src/reducers/entries.js

75 lines
2.4 KiB
JavaScript
Raw Normal View History

import { Map, List, fromJS } from 'immutable';
import {
ENTRY_REQUEST,
ENTRY_SUCCESS,
2017-01-10 22:23:22 -02:00
ENTRY_FAILURE,
ENTRIES_REQUEST,
ENTRIES_SUCCESS,
} from '../actions/entries';
import { SEARCH_ENTRIES_SUCCESS } from '../actions/search';
let collection;
let loadedEntries;
let page;
2016-06-16 22:49:48 -03:00
const entries = (state = Map({ entities: Map(), pages: Map() }), action) => {
switch (action.type) {
case ENTRY_REQUEST:
return state.setIn(['entities', `${ action.payload.collection }.${ action.payload.slug }`, 'isFetching'], true);
2016-09-06 13:04:17 -03:00
case ENTRY_SUCCESS:
return state.setIn(
['entities', `${ action.payload.collection }.${ action.payload.entry.slug }`],
fromJS(action.payload.entry)
);
2016-09-06 13:04:17 -03:00
case ENTRIES_REQUEST:
return state.setIn(['pages', action.payload.collection, 'isFetching'], true);
2016-09-06 13:04:17 -03:00
case ENTRIES_SUCCESS:
collection = action.payload.collection;
loadedEntries = action.payload.entries;
page = action.payload.page;
return state.withMutations((map) => {
loadedEntries.forEach(entry => (
map.setIn(['entities', `${ collection }.${ entry.slug }`], fromJS(entry).set('isFetching', false))
));
const ids = List(loadedEntries.map(entry => entry.slug));
map.setIn(['pages', collection], Map({
page,
2016-10-20 11:30:29 -02:00
ids: (!page || page === 0) ? ids : map.getIn(['pages', collection, 'ids'], List()).concat(ids),
}));
});
2017-01-10 22:23:22 -02:00
case ENTRY_FAILURE:
return state.withMutations((map) => {
map.setIn(['entities', `${ action.payload.collection }.${ action.payload.slug }`, 'isFetching'], false);
map.setIn(['entities', `${ action.payload.collection }.${ action.payload.slug }`, 'error'], action.payload.error.message);
});
case SEARCH_ENTRIES_SUCCESS:
loadedEntries = action.payload.entries;
return state.withMutations((map) => {
loadedEntries.forEach(entry => (
map.setIn(['entities', `${ entry.collection }.${ entry.slug }`], fromJS(entry).set('isFetching', false))
));
});
2016-09-06 13:04:17 -03:00
default:
return state;
}
2016-06-10 00:16:01 -03:00
};
2016-06-10 00:16:01 -03:00
export const selectEntry = (state, collection, slug) => (
state.getIn(['entities', `${ collection }.${ slug }`])
2016-06-10 00:16:01 -03:00
);
2016-06-10 00:16:01 -03:00
export const selectEntries = (state, collection) => {
const slugs = state.getIn(['pages', collection, 'ids']);
return slugs && slugs.map(slug => selectEntry(state, collection, slug));
2016-06-10 00:16:01 -03:00
};
export default entries;