-
-
Save restlessmedia/e957a94d8b0c5bdb97f7170262605207 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const createPaginator = (endpoint, resultKey) => { | |
const createRequestPageActionCreator = (endpoint, resultKey) => (page) => requestPage(endpoint, resultKey, page) | |
const requestPage = (page) => ({ | |
type: 'REQUEST_PAGE', | |
payload: { | |
page | |
}, | |
meta: { | |
endpoint, | |
resultKey | |
} | |
}) | |
const receivePage = (page, results) => ({ | |
type: 'RECEIVE_PAGE', | |
payload: { | |
page, | |
results | |
} | |
}) | |
const pages = (pages = {}, action = {}) => { | |
switch (action.type) { | |
case 'REQUEST_PAGE': | |
return { | |
...pages, | |
[action.payload.page]: { | |
ids: [], | |
fetching: true | |
} | |
} | |
case 'RECEIVE_PAGE': | |
return { | |
...pages, | |
[action.payload.page]: { | |
ids: action.payload.results.filter(item => item.id), | |
fetching: false | |
} | |
} | |
default: | |
return pages | |
} | |
} | |
const currentPage = (currentPage = 1, action = {}) => | |
action.type == 'REQUEST_PAGE' ? action.payload.page : currentPage | |
const onlyForEndpoint = (reducer) => (state = {}, action = {}) => | |
typeof action.meta == 'undefined' ? state : action.meta.endpoint == endpoint ? reducer(state, action) : state | |
const itemsReducer = (items = {}, action = {}) =>{ | |
switch (action.type) { | |
case 'RECEIVE_PAGE': | |
let _items = {} | |
for (let item of action.payload.results) { | |
_items = { | |
..._items, | |
[item.id]: item | |
} | |
} | |
return { | |
...items, | |
..._items | |
} | |
default: | |
return items | |
} | |
} | |
const reducer = onlyForEndpoint( | |
combineReducers({ | |
pages, | |
currentPage | |
}) | |
) | |
return { | |
requestPage, | |
receivePage, | |
reducer, | |
itemsReducer: onlyForEndpoint(itemsReducer) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment