All files / src/utility mapping.js

100% Statements 25/25
100% Branches 18/18
100% Functions 8/8
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 62 63                    15x 12x 12x 50x   30x 30x       12x     15x 5x 3x 10x     10x 10x 29x 1x       10x       2x                   7x 5x 11x   5x 4x       3x      
import {
  each,
  find,
  isArray,
  isNil,
  keys,
  map,
  template,
} from 'lodash';
 
const mapItem = (schema, item) => {
  const mappedItem = {};
  each(schema, (field) => {
    if (!isNil(item[field.name])) {
      // Add mapped value and mask if set
      const fieldName = field.mapName ? field.mapName : field.name;
      mappedItem[fieldName] = field.mask ? template(field.mask)(item) : item[field.name];
    }
  });
 
  return mappedItem;
};
 
const mapNestedSource = (source, schema) => {
  if (isArray(source)) {
    return map(source, (item) => {
      const mappedItem = mapItem(schema, item);
 
      // Loop trough nested items
      const itemKeys = keys(mappedItem);
      map(itemKeys, (key) => {
        if (isArray(mappedItem[key]) && mappedItem[key].length) {
          mappedItem[key] = mapNestedSource(mappedItem[key], schema);
        }
      });
 
      return mappedItem;
    });
  }
 
  return mapItem(schema, source);
};
 
export default {
  /*
  To handle all kinds of mapping we are creating original
  properties for each item. This is double loop and maybe
  should be optimized once nesting is implemented.
  */
  mapWithSchema(schema, source) {
    if (isArray(schema)) {
      const hasMapping = !isNil(find(schema, field => !isNil(field.mapName)));
      const hasMask = !isNil(find(schema, field => !isNil(field.mask)));
 
      if (hasMapping || hasMask) {
        return mapNestedSource(source, schema);
      }
    }
 
    return source;
  },
};