all files / src/ selectors.js

91.67% Statements 22/24
57.14% Branches 4/7
87.5% Functions 7/8
94.74% Lines 18/19
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              21×                              
import pickBy from 'lodash/pickBy';
import isEmpty from 'lodash/isEmpty';
import values from 'lodash/values';
import { denormalize } from 'entman-denormalizr';
 
 
export function getEntitiesSlice(state) {
  return state.entities;
}
 
 
export function getEntities(state, schema, ids) {
  const key = schema.key;
  const entitiesState = getEntitiesSlice(state);
  const entities = ids ?
    values(entitiesState[key]).filter(e => ids.includes(e.id)) : values(entitiesState[key]);
  return entities.map(e => denormalize(e, entitiesState, schema));
}
 
 
export function getEntitiesBy(state, schema, by={}) {
  const byKey = Object.keys(by)[0];
  const value = by[byKey];
  const key = schema.key;
  const entitiesState = getEntitiesSlice(state);
  const entities = values(pickBy(entitiesState[key], e => e[byKey] === value));
  return entities.map(e => denormalize(e, entitiesState, schema));
}
 
 
export function getEntity(state, schema, id) {
  if ( ! id) throw new Error('Required param `id` is missing');
  const key = schema.key;
  const entitiesState = getEntitiesSlice(state);
  const entities = entitiesState[key];
  Iif (isEmpty(entities)) return null;
  const entity = entities[id];
  return denormalize(entity, entitiesState, schema);
}