Guest User

Untitled

a guest
Feb 20th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. import union from 'lodash/union'
  2. import { handleActions } from 'redux-actions'
  3. import { initialState } from 'mocks/state/initialState'
  4. import { set } from 'dot-prop-immutable'
  5.  
  6. // creates a reducer managing pagination
  7. const paginationReducer = ({ types }) => {
  8. if (!Array.isArray(types) || types.length !== 4) {
  9. throw new Error('Expected types to be an array of four elements.')
  10. }
  11. if (!types.every(t => typeof t === 'string')) {
  12. throw new Error('Expected types to be strings.')
  13. }
  14.  
  15. const [requestType, successType, failureType, clearSearchType] = types
  16.  
  17. const updatePagination = handleActions({
  18. [`${requestType}`]: (state, action) => {
  19. state = set(state, 'fetching', true)
  20.  
  21. return state
  22. },
  23. [`${successType}`]: (state, action) => {
  24. const { result } = action.payload.response
  25. const ids = union(state.ids, Array.isArray(result) ? result : [result])
  26.  
  27. state = set(state, 'fetching', false)
  28. state = set(state, 'ids', ids)
  29.  
  30. return state
  31. },
  32. [`${failureType}`]: (state, action) => {
  33. state = set(state, 'fetching', false)
  34. return state
  35. }
  36. }, {
  37. fetching: false,
  38. ids: []
  39. })
  40.  
  41. return handleActions({
  42. [`${requestType}`]: (state, action) => {
  43. const { limit, skip, term } = action.meta.params
  44.  
  45. if (term) {
  46. state = set(state, 'search', { term })
  47. state = set(state, 'search', updatePagination(state.search, action))
  48. } else {
  49. state = set(state, 'limit', limit)
  50. state = set(state, 'skip', skip)
  51. state = set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
  52. }
  53.  
  54. return state
  55. },
  56. [`${successType}`]: (state, action) => {
  57. const { limit, skip, search } = state
  58. state = search.fetching
  59. ? set(state, 'search', updatePagination(state.search, action))
  60. : set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
  61.  
  62. return state
  63. },
  64. [`${failureType}`]: (state, action) => {
  65. const { limit, skip, search } = state
  66.  
  67. state = search.fetching
  68. ? set(state, 'search', updatePagination(state.search, action))
  69. : set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
  70.  
  71. return state
  72. },
  73. [`${clearSearchType}`]: (state, action) => {
  74. state = set(state, 'search', { fetching: false, ids: [] })
  75. return state
  76. }
  77. }, initialState)
  78. }
  79.  
  80. export default paginationReducer
Add Comment
Please, Sign In to add comment