all files / src/reducer/ entity.js

100% Statements 18/18
100% Branches 10/10
100% Functions 6/6
100% Lines 18/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61              15× 15×                                     11× 11×         174×   15×         11×         136× 136×          
import omit from 'lodash/omit';
 
import { update, defaultTo } from 'utils';
import createReactions from './create-reactions';
 
 
function createEntity(state, action) {
  const { entity } = action.payload;
  return { ...state, [entity.id]: entity };
}
 
 
function updateEntity(state, action) {
  const { entity, useDefault } = action.payload;
  const data = omit(entity, 'id');
  return {
    ...state,
    [entity.id]: useDefault ? defaultTo(state[entity.id], data) : update(state[entity.id], data),
  };
}
 
 
function updateEntityId(state, action) {
  const { oldId, newId } = action.payload;
  return {
    ...omit(state, oldId),
    [newId]: { ...state[oldId], id: newId },
  };
}
 
 
function deleteEntity(state, action) {
  const { entity } = action.payload;
  return omit(state, entity.id);
}
 
 
export default function createEntityReducer(schema) {
  const reactions = createReactions(schema.getRelations());
  return (state={}, action) => {
    switch (action.type) {
      case `@@entman/CREATE_ENTITY_${schema.key.toUpperCase()}`: {
        return createEntity(state, action);
      }
      case `@@entman/UPDATE_ENTITY_${schema.key.toUpperCase()}`: {
        return updateEntity(state, action);
      }
      case `@@entman/DELETE_ENTITY_${schema.key.toUpperCase()}`: {
        return deleteEntity(state, action);
      }
      case `@@entman/UPDATE_ENTITY_ID_${schema.key.toUpperCase()}`: {
        return updateEntityId(state, action);
      }
      default: {
        const reaction = reactions[action.type];
        return (typeof reaction === 'function') ? reaction(state, action) : state;
      }
    }
  };
}