({ types, mapActionToKey })
| 3 | // Creates a reducer managing pagination, given the action types to handle, |
| 4 | // and a function telling how to extract the key from an action. |
| 5 | const paginate = ({ types, mapActionToKey }) => { |
| 6 | if (!Array.isArray(types) || types.length !== 3) { |
| 7 | throw new Error('Expected types to be an array of three elements.') |
| 8 | } |
| 9 | if (!types.every(t => typeof t === 'string')) { |
| 10 | throw new Error('Expected types to be strings.') |
| 11 | } |
| 12 | if (typeof mapActionToKey !== 'function') { |
| 13 | throw new Error('Expected mapActionToKey to be a function.') |
| 14 | } |
| 15 | |
| 16 | const [ requestType, successType, failureType ] = types |
| 17 | |
| 18 | const updatePagination = (state = { |
| 19 | isFetching: false, |
| 20 | nextPageUrl: undefined, |
| 21 | pageCount: 0, |
| 22 | ids: [] |
| 23 | }, action) => { |
| 24 | switch (action.type) { |
| 25 | case requestType: |
| 26 | return { |
| 27 | ...state, |
| 28 | isFetching: true |
| 29 | } |
| 30 | case successType: |
| 31 | return { |
| 32 | ...state, |
| 33 | isFetching: false, |
| 34 | ids: union(state.ids, action.response.result), |
| 35 | nextPageUrl: action.response.nextPageUrl, |
| 36 | pageCount: state.pageCount + 1 |
| 37 | } |
| 38 | case failureType: |
| 39 | return { |
| 40 | ...state, |
| 41 | isFetching: false |
| 42 | } |
| 43 | default: |
| 44 | return state |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | return (state = {}, action) => { |
| 49 | // Update pagination by key |
| 50 | switch (action.type) { |
| 51 | case requestType: |
| 52 | case successType: |
| 53 | case failureType: |
| 54 | const key = mapActionToKey(action) |
| 55 | if (typeof key !== 'string') { |
| 56 | throw new Error('Expected key to be a string.') |
| 57 | } |
| 58 | return { |
| 59 | ...state, |
| 60 | [key]: updatePagination(state[key], action) |
| 61 | } |
| 62 | default: |
no test coverage detected