1 import { chainClient } from 'utility/environment'
2 import { push, replace } from 'react-router-redux'
4 export default function(type, options = {}) {
5 const listPath = options.listPath || `/${type}s`
6 const clientApi = () => options.clientApi ? options.clientApi() : chainClient()[`${type}s`]
8 const receive = (param) => ({
9 type: `RECEIVED_${type.toUpperCase()}_ITEMS`,
13 // Dispatch a single request for the specified query, and persist the
14 // results to the default item store
15 const fetchItems = (params) => {
16 const requiredParams = options.requiredParams || {}
18 params = { ...params, ...requiredParams }
20 return (dispatch) => {
21 const promise = clientApi().query(params)
25 if(resp.status == 'fail'){
26 dispatch({type: 'ERROR', payload: { 'message': resp.msg}})
28 dispatch(receive(resp))
37 // Fetch all items up to the specified page, and persist the results to
38 // the filter-specific store
39 const fetchPage = (query, pageNumber = 1, options = {}) => {
40 const listId = query.filter || ''
41 pageNumber = parseInt(pageNumber || 1)
43 return (dispatch, getState) => {
44 const getFilterStore = () => getState()[type].queries[listId] || {}
46 const fetchNextPage = () =>
47 dispatch(_load(query, getFilterStore(), options)).then((resp) => {
48 if (!resp || resp.type == 'ERROR') return
50 return Promise.resolve(resp)
53 return dispatch(fetchNextPage)
57 // Fetch and persist all records of the current object type
58 const fetchAll = () => {
59 return fetchPage('', -1)
62 const _load = function(query = {}, list = {}, requestOptions) {
63 return function(dispatch) {
64 const latestResponse = list.cursor || null
65 const refresh = requestOptions.refresh || false
67 if (!refresh && latestResponse && latestResponse.lastPage) {
68 return Promise.resolve({last: true})
72 const filter = query.filter || ''
74 if (!refresh && latestResponse) {
76 promise = latestResponse.nextPage()
79 return dispatch(receive(responsePage))
85 if (query.filter) params.filter = filter
86 if (query.sumBy) params.sumBy = query.sumBy.split(',')
88 promise = dispatch(fetchItems(params))
91 return promise.then((response) => {
93 type: `APPEND_${type.toUpperCase()}_PAGE`,
98 return dispatch({type: 'ERROR', payload: err})
103 const deleteItem = (id, confirmMessage, deleteMessage) => {
104 return (dispatch) => {
105 if (!window.confirm(confirmMessage)) {
109 clientApi().delete(id)
110 .then(() => dispatch({
111 type: `DELETE_${type.toUpperCase()}`,
113 message: deleteMessage,
114 })).catch(err => dispatch({
115 type: 'ERROR', payload: err
120 const pushList = (query = {}, pageNumber, options = {}) => {
133 if (options.replace) return replace(location)
134 return push(location)
143 didLoadAutocomplete: {
144 type: `DID_LOAD_${type.toUpperCase()}_AUTOCOMPLETE`