2016-12-07 15:44:07 -02:00
|
|
|
import { Map, List } from 'immutable';
|
|
|
|
|
|
|
|
import {
|
|
|
|
SEARCH_ENTRIES_REQUEST,
|
|
|
|
SEARCH_ENTRIES_SUCCESS,
|
|
|
|
QUERY_REQUEST,
|
|
|
|
QUERY_SUCCESS,
|
|
|
|
SEARCH_CLEAR,
|
|
|
|
} from '../actions/search';
|
|
|
|
|
|
|
|
let loadedEntries;
|
|
|
|
let response;
|
|
|
|
let page;
|
|
|
|
let searchTerm;
|
|
|
|
|
2017-01-19 15:50:26 -02:00
|
|
|
const defaultState = Map({ isFetching: false, term: null, page: 0, entryIds: List([]), queryHits: Map({}) });
|
2016-12-07 15:44:07 -02:00
|
|
|
|
|
|
|
const entries = (state = defaultState, action) => {
|
|
|
|
switch (action.type) {
|
|
|
|
case SEARCH_CLEAR:
|
|
|
|
return defaultState;
|
|
|
|
|
|
|
|
case SEARCH_ENTRIES_REQUEST:
|
|
|
|
if (action.payload.searchTerm !== state.get('term')) {
|
|
|
|
return state.withMutations((map) => {
|
|
|
|
map.set('isFetching', true);
|
|
|
|
map.set('term', action.payload.searchTerm);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return state;
|
|
|
|
|
|
|
|
case SEARCH_ENTRIES_SUCCESS:
|
|
|
|
loadedEntries = action.payload.entries;
|
|
|
|
page = action.payload.page;
|
|
|
|
searchTerm = action.payload.searchTerm;
|
|
|
|
return state.withMutations((map) => {
|
|
|
|
const entryIds = List(loadedEntries.map(entry => ({ collection: entry.collection, slug: entry.slug })));
|
|
|
|
map.set('isFetching', false);
|
|
|
|
map.set('page', page);
|
|
|
|
map.set('term', searchTerm);
|
|
|
|
map.set('entryIds', page === 0 ? entryIds : map.get('entryIds', List()).concat(entryIds));
|
|
|
|
});
|
|
|
|
|
|
|
|
case QUERY_REQUEST:
|
|
|
|
if (action.payload.searchTerm !== state.get('term')) {
|
|
|
|
return state.withMutations((map) => {
|
2016-12-29 17:18:24 -02:00
|
|
|
map.set('isFetching', action.payload.namespace);
|
2016-12-07 15:44:07 -02:00
|
|
|
map.set('term', action.payload.searchTerm);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return state;
|
|
|
|
|
|
|
|
case QUERY_SUCCESS:
|
|
|
|
searchTerm = action.payload.searchTerm;
|
|
|
|
response = action.payload.response;
|
|
|
|
return state.withMutations((map) => {
|
|
|
|
map.set('isFetching', false);
|
|
|
|
map.set('term', searchTerm);
|
2016-12-29 17:18:24 -02:00
|
|
|
map.set('queryHits', Map({ [action.payload.namespace]: response.hits }));
|
2016-12-07 15:44:07 -02:00
|
|
|
});
|
|
|
|
|
|
|
|
default:
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export default entries;
|