filters.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { FILTERS_IMPORT } from '../actions/importer';
  2. import { FILTERS_FETCH_SUCCESS, FILTERS_CREATE_SUCCESS } from '../actions/filters';
  3. import { Map as ImmutableMap, is, fromJS } from 'immutable';
  4. const normalizeFilter = (state, filter) => {
  5. const normalizedFilter = fromJS({
  6. id: filter.id,
  7. title: filter.title,
  8. context: filter.context,
  9. filter_action: filter.filter_action,
  10. keywords: filter.keywords,
  11. expires_at: filter.expires_at ? Date.parse(filter.expires_at) : null,
  12. });
  13. if (is(state.get(filter.id), normalizedFilter)) {
  14. return state;
  15. } else {
  16. // Do not overwrite keywords when receiving a partial filter
  17. return state.update(filter.id, ImmutableMap(), (old) => (
  18. old.mergeWith(((old_value, new_value) => (new_value === undefined ? old_value : new_value)), normalizedFilter)
  19. ));
  20. }
  21. };
  22. const normalizeFilters = (state, filters) => {
  23. filters.forEach(filter => {
  24. state = normalizeFilter(state, filter);
  25. });
  26. return state;
  27. };
  28. export default function filters(state = ImmutableMap(), action) {
  29. switch(action.type) {
  30. case FILTERS_CREATE_SUCCESS:
  31. return normalizeFilter(state, action.filter);
  32. case FILTERS_FETCH_SUCCESS:
  33. return normalizeFilters(ImmutableMap(), action.filters);
  34. case FILTERS_IMPORT:
  35. return normalizeFilters(state, action.filters);
  36. default:
  37. return state;
  38. }
  39. };