@plone/volto
Version:
Volto
133 lines (128 loc) • 3.35 kB
JavaScript
/**
* Search reducer.
* @module reducers/search/search
*/
import map from 'lodash/map';
import omit from 'lodash/omit';
import { flattenToAppURL } from '@plone/volto/helpers/Url/Url';
import {
RESET_SEARCH_CONTENT,
SEARCH_CONTENT,
} from '@plone/volto/constants/ActionTypes';
const initialState = {
error: null,
items: [],
total: 0,
loaded: false,
loading: false,
batching: {},
subrequests: {},
};
/**
* Search reducer.
* @function search
* @param {Object} state Current state.
* @param {Object} action Action to be handled.
* @returns {Object} New state.
*/
export default function search(state = initialState, action = {}) {
switch (action.type) {
case `${SEARCH_CONTENT}_PENDING`:
return action.subrequest
? {
...state,
subrequests: {
...state.subrequests,
[action.subrequest]: {
...(state.subrequests[action.subrequest] || {
items: [],
total: 0,
batching: {},
}),
error: null,
loaded: false,
loading: true,
},
},
}
: {
...state,
error: null,
loading: true,
loaded: false,
};
case `${SEARCH_CONTENT}_SUCCESS`:
return action.subrequest
? {
...state,
subrequests: {
...state.subrequests,
[action.subrequest]: {
error: null,
items: map(action.result.items, (item) => ({
...item,
'@id': flattenToAppURL(item['@id']),
})),
total: action.result.items_total,
loaded: true,
loading: false,
batching: { ...action.result.batching },
},
},
}
: {
...state,
error: null,
items: map(action.result.items, (item) => ({
...item,
'@id': flattenToAppURL(item['@id']),
})),
total: action.result.items_total,
loaded: true,
loading: false,
batching: { ...action.result.batching },
};
case `${SEARCH_CONTENT}_FAIL`:
return action.subrequest
? {
...state,
subrequests: {
...state.subrequests,
[action.subrequest]: {
error: action.error,
items: [],
total: 0,
loading: false,
loaded: false,
batching: {},
},
},
}
: {
...state,
error: action.error,
items: [],
total: 0,
loading: false,
loaded: false,
batching: {},
};
case RESET_SEARCH_CONTENT:
return action.subrequest
? {
...state,
subrequests: omit(state.subrequests, [action.subrequest]),
}
: {
...state,
error: null,
items: [],
total: 0,
loading: false,
loaded: false,
batching: {},
};
default:
return state;
}
}