|
import rest from './rest'; |
|
|
|
/* |
|
* Store similar to redux-api that handles multiple requests. |
|
* |
|
* redux-api is fine when you want to request a single resource. But when you'd like |
|
* to fetch a number of similar resources, e.g. all products a user just selected, with |
|
* each their own api call, it isn't sufficient on its own. |
|
* |
|
* This store performs redux-api requests on multiple resources at once, and puts them |
|
* under a single entry in the store. |
|
* |
|
* It's not a fully general solution like redux-api, but it may be come in the future, perhaps. |
|
* |
|
*/ |
|
|
|
function productHistograms({groupParam, groupValues, ...params}) { |
|
return (dispatch, getState) => { |
|
dispatch({type: 'REST_MULTI_RESET', key: 'productHistograms', count: groupValues.length}); |
|
groupValues.forEach(value => { |
|
const requestParams = {...params, [groupParam]: value}; |
|
rest.actions.productHistogram.request(requestParams).then(data => { |
|
const histogramData = ((data || {}).products_histogram || {}).data; |
|
dispatch({type: 'REST_MULTI_UPDATE', key: 'productHistograms', groupValue: value, data: histogramData}); |
|
}); |
|
}); |
|
}; |
|
} |
|
|
|
export const actions = {productHistograms}; |
|
|
|
const initialState = { |
|
sync: false, // `true` when all requests have finished succesfully |
|
count: null, // used internally, don't depend too much on this number of requests to make |
|
data: {}, // keys are `groupValues`, values the api result |
|
}; |
|
|
|
function makeReducer(name) { |
|
return function(state = initialState, action) { |
|
if (action.type === 'REST_MULTI_RESET' && action.key === name) { |
|
return {...initialState, count: action.count}; |
|
} else if (action.type === 'REST_MULTI_UPDATE' && action.key === name) { |
|
const newData = {...state.data, [action.groupValue]: action.data}; |
|
const sync = Object.keys(newData).length >= state.count; |
|
return {...state, sync, data: newData}; |
|
} else { |
|
return state; |
|
} |
|
}; |
|
} |
|
|
|
export const reducers = { |
|
productHistograms: makeReducer('productHistograms'), |
|
}; |
|
|
|
const RestMulti = {actions, reducers}; |
|
export default RestMulti; |