static-cms/src/reducers/entries.js

85 lines
2.9 KiB
JavaScript
Raw Normal View History

import { Map, List, fromJS } from 'immutable';
import {
ENTRY_REQUEST, ENTRY_SUCCESS, ENTRIES_REQUEST, ENTRIES_SUCCESS, SEARCH_ENTRIES_REQUEST, SEARCH_ENTRIES_SUCCESS
} from '../actions/entries';
let collection, loadedEntries, page, searchTerm;
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: page,
ids: page === 0 ? ids : map.getIn(['pages', collection, 'ids'], List()).concat(ids)
}));
});
case SEARCH_ENTRIES_REQUEST:
if (action.payload.searchTerm !== state.getIn(['search', 'term'])) {
return state.withMutations((map) => {
map.setIn(['search', 'isFetching'], true);
map.setIn(['search', 'term'], action.payload.searchTerm);
});
} else {
return state;
}
case SEARCH_ENTRIES_SUCCESS:
loadedEntries = action.payload.entries;
page = action.payload.page;
searchTerm = action.payload.searchTerm;
return state.withMutations((map) => {
loadedEntries.forEach((entry) => (
map.setIn(['entities', `${entry.collection}.${entry.slug}`], fromJS(entry).set('isFetching', false))
));
const ids = List(loadedEntries.map(entry => ({ collection: entry.collection, slug: entry.slug })));
map.set('search', Map({
page: page,
term: searchTerm,
ids: page === 0 ? ids : map.getIn(['search', 'ids'], List()).concat(ids)
}));
});
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
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 const selectSearchedEntries = (state) => {
const searchItems = state.getIn(['search', 'ids']);
return searchItems && searchItems.map(({ collection, slug }) => selectEntry(state, collection, slug));
};
2016-06-10 00:16:01 -03:00
export default entries;