Home Reference Source

application/redux/reducers/entry-reducers.js

  1. import _ from 'lodash';
  2. import Immutable from 'immutable';
  3. import {
  4. ENTRIES_REQUEST,
  5. ENTRIES_RECEIVE,
  6. ENTRIES_RECEIVE_PAGINATION,
  7. ENTRY_RECEIVE,
  8. ENTRIES_INVALIDATE,
  9. ENTRY_SELECTED,
  10. ENTRIES_SET_PAGE
  11. } from './../actions/entry-actions';
  12.  
  13. const PER_PAGE = 20;
  14.  
  15. export function entries(state = null, action) {
  16. if (state === null) {
  17. state = {
  18. isFetching: false,
  19. didInvalidate: false,
  20. items: Immutable.fromJS({}),
  21. selected: false,
  22. page: 0,
  23. pagination: {
  24. before: 0,
  25. current: 0,
  26. first: 0,
  27. last: 0,
  28. limit: 0,
  29. next: 0,
  30. total_items: 0,
  31. total_pages: 0
  32. },
  33. order: "name",
  34. dir: "asc",
  35. filter: false
  36. };
  37. }
  38.  
  39. let newState;
  40.  
  41. switch (action.type) {
  42. case ENTRIES_RECEIVE_PAGINATION:
  43. return Object.assign({}, state, {
  44. pagination: {
  45. 'before': action.payload.before,
  46. 'current': action.payload.current,
  47. 'first': action.payload.first,
  48. 'last': action.payload.last,
  49. 'limit': action.payload.limit,
  50. 'next': action.payload.next,
  51. 'total_items': action.payload.total_items,
  52. 'total_pages': action.payload.total_pages,
  53. }
  54. });
  55. case ENTRIES_INVALIDATE:
  56. return Object.assign({}, state, {
  57. didInvalidate: true,
  58. });
  59. case ENTRIES_REQUEST:
  60. return Object.assign({}, state, {
  61. isFetching: true,
  62. didInvalidate: false
  63. });
  64. case ENTRY_SELECTED: {
  65. return Object.assign({}, state, {
  66. selected: action.payload.selected
  67. });
  68. }
  69. case ENTRY_RECEIVE:
  70. const entry = action.payload.entry;
  71. let found = false;
  72. const allEntries = state.items.map((item, i) => {
  73. if (item.get('uuid') == entry.get('uuid')) {
  74. found = true;
  75. return entry;
  76. }
  77. return item;
  78. });
  79.  
  80. if (!found) {
  81. let temp = allEntries.toList().asMutable();
  82. temp.push(entry);
  83. action.payload.entries = temp.asMutable();
  84. } else {
  85. action.payload.entries = allEntries;
  86. }
  87. case ENTRIES_RECEIVE:
  88. return Object.assign({}, state, {
  89. isFetching: false,
  90. didInvalidate: false,
  91. items: action.payload.entries
  92. });
  93. }
  94.  
  95. return state;
  96. };