poll.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import moment from 'moment';
  2. export const BUSY_POLL = 'BUSY_POLL';
  3. export const RELEASE_POLL = 'RELEASE_POLL';
  4. export const REMOVE_POLL = 'REMOVE_POLL';
  5. export const REPLACE_POLL = 'REPLACE_POLL';
  6. export const UPDATE_POLL = 'UPDATE_POLL';
  7. export function hydrate(json) {
  8. let hasSelectedChoices = false;
  9. for (const i in json.choices) {
  10. const choice = json.choices[i];
  11. if (choice.selected) {
  12. hasSelectedChoices = true;
  13. break;
  14. }
  15. }
  16. return Object.assign({}, json, {
  17. posted_on: moment(json.posted_on),
  18. hasSelectedChoices,
  19. endsOn: (json.length ? moment(json.posted_on).add(json.length, 'days') : null),
  20. isBusy: false
  21. });
  22. }
  23. export function busy() {
  24. return {
  25. type: BUSY_POLL
  26. };
  27. }
  28. export function release() {
  29. return {
  30. type: RELEASE_POLL
  31. };
  32. }
  33. export function replace(newState, hydrated=false) {
  34. return {
  35. type: REPLACE_POLL,
  36. state: hydrated ? newState : hydrate(newState)
  37. };
  38. }
  39. export function update(data) {
  40. return {
  41. type: UPDATE_POLL,
  42. data
  43. };
  44. }
  45. export function remove() {
  46. return {
  47. type: REMOVE_POLL
  48. };
  49. }
  50. export default function poll(state={}, action=null) {
  51. switch (action.type) {
  52. case BUSY_POLL:
  53. return Object.assign({}, state, {isBusy: true});
  54. case RELEASE_POLL:
  55. return Object.assign({}, state, {isBusy: false});
  56. case REMOVE_POLL:
  57. return {
  58. isBusy: false
  59. };
  60. case REPLACE_POLL:
  61. return action.state;
  62. case UPDATE_POLL:
  63. return Object.assign({}, state, action.data);
  64. default:
  65. return state;
  66. }
  67. }