All files actionsToVariables.js

86.42% Statements 70/81
81.54% Branches 53/65
83.33% Functions 15/18
86.11% Lines 62/72

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171                    16x   16x 18x 18x   18x   18x     1x 1x 1x       6x 6x 6x 6x     2x 1x 1x 1x                       1x   2x 2x   2x     3x 1x   2x   3x 3x     3x 1x   2x   3x 3x   3x   2x 1x   1x   2x 2x   1x 1x         16x 16x   16x             30x 14x 14x 18x 16x 6x   12x                                                                           54x 4x 6x   50x 30x   28x               18x 18x 18x 3x 15x 15x         18x  
// @flow
import {update, set, merge, isPlainObject, isArray, mapValues, pickBy} from 'lodash';
 
import type {Action, ActionType} from './types';
import type {CannerSchema} from '../components/types';
 
/**
 * change actions to variables which is the argument of graphql mutation
 */
export default function actionsToVariables(actions: Array<Action<ActionType>>, schema: CannerSchema) {
  const variables = {payload: {}, where: {}};
 
  actions.forEach(action => {
    let {path = '', value, id, relation, key} = action.payload;
    const relationField = genRelationField(schema, key);
   
    value = parseArrayToSet(value, relationField);
    
    switch(action.type) {
      case 'CREATE_ARRAY': {
        // remove null relation
        const ensureValue = pickBy(value, (v, k) => v !== null && k !== '__typename' && relationField.indexOf(k) === -1);
        merge(variables.payload, ensureValue);
        break;
      }
      case 'UPDATE_ARRAY':
      case 'UPDATE_OBJECT': {
        merge(variables.payload, value);
        merge(variables.where, {id});
        variables.payload = removeTypename(variables.payload);
        break;
      }
      case 'CONNECT': {
        if (relation && relation.type === 'toMany') {
          update(variables.payload, path.split('/'), relationField => {
            Eif (isArray(relationField) || !relationField) {
              return {
                connect: [{
                  id: value.id
                }]
              };
            }
            relationField.connect.push({
              id: value.id
            });
            return relationField;
          });
        } else {
          set(variables.payload, path.split('/').concat('connect'), {id: value.id});
        }
        Eif (id) {
          merge(variables.where, {id});
        }
        break;
      }
      case 'CREATE_AND_CONNECT': {
        if (relation && relation.type === 'toMany') {
          update(variables.payload, path.split('/').concat('create'), arr => (arr || []).concat(value));
        } else {
          set(variables.payload, path.split('/').concat('create'), value);
        }
        merge(variables.where, {id});
        break;
      }
      case 'DISCONNECT':
        if (relation && relation.type === 'toMany') {
          update(variables.payload, path.split('/').concat('disconnect'), arr => (arr || []).concat({id: value.id}));
        } else {
          set(variables.payload, path.split('/').concat('disconnect'), true);
        }
        Eif (id) {
          merge(variables.where, {id});
        }
        break;
      case 'DISCONNECT_AND_DELETE':
        if (relation && relation.type === 'toMany') {
          update(variables.payload, path.split('/').concat('delete'), arr => (arr || []).concat(value));
        } else {
          set(variables.payload, path.split('/').concat('delete'), true);
        }
        merge(variables.where, {id});
        break;
      case 'DELETE_ARRAY':
        merge(variables.where, {id});
        break;
      default:
        break;
    }
  });
  Eif (isPlainObject(variables.payload)) {
    delete variables.payload.id;
  }
  return variables;
}
 
/**
 * add typename: null in every object
 */
export function removeTypename(payload: any): any {
  if (isPlainObject(payload)) {
    const newPayload = {...payload};
    delete newPayload.__typename;
    return mapValues(newPayload, value => removeTypename(value));
  } else if (Array.isArray(payload)) {
    return payload.map(item => removeTypename(item));
  }
  return payload;
}
 
export function addTypename(payload: any): any {
  if (isArray(payload)) {
    return payload.map(item => addTypename(item));
  }
  if (isPlainObject(payload)) {
    return mapValues(payload, (item, key) => {
      return key === '__typename' ?
        item :
        addTypename(item)
    });
  } else {
    return payload;
  }
}
 
/**
 * 
 * In canner graphql interface,
 * an array value should become a object with `set` keyword.
 * 
 * for examples:
 * origin payload = {
 *   hobbies: ['basketball', 'swim'] 
 *   name: 'James'
 * }
 * will become
 * {
 *   hobbies: {
 *     set: ['basketball', 'swim']
 *   },
 *   name: 'James'
 * } 
 *
 */
export function parseArrayToSet(payload: any, relationField: Array<string>, key?: string): any {
  if (isArray(payload) && relationField.indexOf(key) === -1) {
    return {
      set: payload.map(v => parseArrayToSet(v, relationField))
    };
  } else if (isPlainObject(payload)) {
    return mapValues(payload, (v, k) => parseArrayToSet(v, relationField, k));
  } else {
    return payload
  }
}
 
/**
 * find the relation field in first level relation
 */
export function genRelationField(schema: Object, key: string): Array<string> {
  const keySchema = schema[key];
  let items = {};
  if (keySchema.type === 'object') {
    items = keySchema.items;
  } else Eif (keySchema.type === 'array') {
    items = keySchema.items.items
  } else {
    return [];
  }
 
  return Object.keys(items).filter((field: string) => items[field].type === 'relation');
}