All files / src/query utils.js

89.17% Statements 107/120
67.12% Branches 49/73
89.47% Functions 17/19
89.92% Lines 107/119

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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                  9x 9x     471x 471x 471x 471x 471x   14x 49x 49x   14x     99x 250x 250x 250x 250x   99x 45x 45x                 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x                       99x       31x 31x 153x 120x 120x 120x 120x                                     31x                                       327x 327x   471x               45x 45x 45x 45x 45x 45x 45x               45x       37x 37x 37x 37x 52x 52x 52x 52x     37x               213x 521x 521x 521x 336x     185x 13x 13x 13x 13x 13x           13x     185x 12x     185x 12x     185x 12x     185x 35x 13x 13x   22x 22x       185x 183x 183x 12x                                 183x   183x   185x   213x       22x   91x 3x   88x     88x 88x         13x   18x 3x   15x     15x 15x         270x 270x           90x    
// @flow
 
import pluralize from 'pluralize';
import lowerFirst from 'lodash/lowerFirst';
import upperFirst from 'lodash/upperFirst';
import {merge, mapValues, set} from 'lodash';
import {createSchema} from './schema/utils';
import {types} from './schema/types';
 
const DEFAULT_FIRST = 10;
const MAX = undefined;
 
export function fieldToQueriesObject(field: any): any {
  let queriesObj = {};
  const variables = {};
  let variableTypes = {};
  const type = field.getType();
  switch (type) {
    case types.OBJECT: {
      field.forEach(childField => {
        const qlo = fieldToQueriesObject(childField);
        set(queriesObj, ['fields', childField.getKey()], qlo.queriesObj);
      });
      break;
    }
    case types.ARRAY: {
      field.forEach(childField => {
        const qlo = fieldToQueriesObject(childField);
        set(queriesObj, ['fields', childField.getKey()], qlo.queriesObj);
        merge(variables, qlo.variables);
        merge(variableTypes, qlo.variableTypes);
      });
      if (field.isEntity) {
        const {args, firstKey, afterKey, lastKey, beforeKey, whereKey, orderByKey} = genQuery();
        queriesObj.declareArgs = {
          ...variableTypes,
          [firstKey]: 'Int',
          [afterKey]: 'String',
          [lastKey]: 'Int',
          [beforeKey]: 'String',
          [whereKey]: `${typeKey(field.getKey())}WhereInput`,
          [orderByKey]: `${typeKey(field.getKey())}OrderByInput`
        };
        queriesObj.args = args;
        queriesObj.isPlural = true;
        queriesObj.connection = true;
        queriesObj.alias = field.getKey();
        set(queriesObj, ['fields', 'id'], null);
        variables[firstKey] = MAX;
        variables[whereKey] = {};
        const toolbar = field.getAttr('toolbar');
        const asyncToolbar = toolbar && toolbar.async;
        const defaultSortField = toolbar && toolbar.sorter && toolbar.sorter.defaultField;
        const permanentFilter = toolbar && toolbar.filter && toolbar.filter.permanentFilter;
        Iif (asyncToolbar) {
          variables[firstKey] = DEFAULT_FIRST;
          if (permanentFilter) {
            variables[whereKey] = permanentFilter;
          }
          if (defaultSortField) {
            const field = (toolbar.sorter.options || []).find(option => option.field === defaultSortField);
            const defaultOrder = field && field.defaultOrder ? field.defaultOrder.toUpperCase() : 'ASC';
            variables[orderByKey] = `${defaultSortField}_${defaultOrder}`
          }
        }
      }
      break;
    }
 
    case types.RELATION: {
      set(queriesObj, ['fields', 'id'], null);
      field.forEach(childField => {
        if (childField.getType() !== types.RELATION) {
          const qlo = fieldToQueriesObject(childField);
          set(queriesObj, ['fields', childField.getKey()], qlo.queriesObj);
          merge(variables, qlo.variables);
          merge(variableTypes, qlo.variableTypes);
        }
      });
      // for now, fetch all toMany data
      // if (field.isToMany()) {
      //   const {args, firstKey, afterKey, lastKey, beforeKey, whereKey, orderByKey} = genQuery();
      //   queriesObj.args = args;
      //   queriesObj.isPlural = true;
      //   variables[firstKey] = defaultFirst;
      //   variableTypes = {
      //     ...variableTypes,
      //     [firstKey]: 'Int',
      //     [afterKey]: 'String',
      //     [lastKey]: 'Int',
      //     [beforeKey]: 'String',
      //     [whereKey]: `${typeKey(field.relationTo())}WhereUniqueInput`,
      //     [orderByKey]: `${typeKey(field.relationTo())}WhereUniqueInput`
      //   }
      // }
      break;
    }
 
    case types.DATETIME:
    case types.FILE:
    case types.GEOPOINT:
    case types.IMAGE: {
      field.forEach(childField => {
        const qlo = fieldToQueriesObject(childField);
        set(queriesObj, ['fields', childField.getKey()], qlo.queriesObj);
      });
      break;
    }
    case types.BOOLEAN:
    case types.NUMBER:
    case types.INT:
    case types.ID:
    case types.STRING:
    case types.JSON:
    default:
      queriesObj = null;
      break;
  }
  return {
    queriesObj,
    variables,
    variableTypes
  };
}
 
export function genQuery() {
  const firstKey = randomKey();
  const afterKey = randomKey();
  const lastKey = randomKey();
  const beforeKey = randomKey();
  const whereKey = randomKey();
  const orderByKey = randomKey();
  const args = {
    first: firstKey,
    after: afterKey,
    last: lastKey,
    before: beforeKey,
    where: whereKey,
    orderBy: orderByKey
  };
  return {args, firstKey, afterKey, lastKey, beforeKey, whereKey, orderByKey};
}
 
export function schemaToQueriesObject(schema: any) {
  const rootFields = createSchema(schema);
  const rootVariables = {};
  let rootVariableTypes = {};
  const queriesObj = mapValues(rootFields, (v, key) => {
    const {variables, queriesObj, variableTypes} = fieldToQueriesObject(v);
    merge(rootVariables, variables);
    rootVariableTypes[key] = variableTypes;
    return queriesObj;
  });
 
  return {
    queriesObj,
    variables: rootVariables
  }
}
 
export function objectToQueries(o: Object, close: boolean = true, variables?: Object) {
 
  const result = Object.keys(o).map(key => {
    let query = `${key}`;
    let element = o[key];
    if (!element) {
      return `${query}`;
    }
 
    if (element.declareArgs) {
      const originElement = {...element};
      const args = originElement.declareArgs;
      delete originElement.declareArgs;
      query = 'query';
      element = {
        args,
        fields: {
          [key]: originElement
        }
      };
      key = 'query';
    }
 
    if (element.isPlural) {
      query = pluralize.plural(lowerFirst(query));
    }
 
    if (element.connection) {
      query = `${query}Connection`;
    }
 
    if (element.alias) {
      query = `${element.alias}: ${query}`;
    }
 
    if (element.args) {
      if (key === 'query') {
        const args = genDeclareArgs(element.args, variables);
        query = args ? `${query}(${args})` : `${query}`;
      } else {
        const args = genArgs(element.args, variables);
        query = args ? `${query}(${args})` : `${query}`;
      }
    }
 
    if (element.fields) {
      let {fields} = element;
      if (element.connection) {
        fields = {
          edges: {
            fields: {
              cursor: null,
              node: {
                fields
              }
            }
          },
          pageInfo: {
            fields: {
              hasNextPage: null,
              hasPreviousPage: null
            }
          }
        }
      }
      fields = objectToQueries(fields, true, variables);
      
      query = `${query}${fields}`;
    }
    return `${query}`;
  }).join(' ');
  return close ? `{${result}}` : result;
}
 
function genArgs(args, variables) {
  return Object.keys(args)
    .filter(key => {
      if (variables && variables[args[key].substr(1)] === undefined) {
        return false;
      }
      return true;
    })
    .map(key => {
      const argValue = args[key];
      return `${key}: ${argValue}`
    }).join(',');
}
 
function genDeclareArgs(args, variables) {
  return Object.keys(args)
    .filter(key => {
      if (variables && variables[key.substr(1)] === undefined) {
        return false;
      }
      return true;
    })
    .map(key => {
      const argValue = args[key];
      return `${key}: ${argValue}`
    }).join(',');
}
 
function randomKey () {
  Eif (process.env.NODE_ENV === 'test') {
    return `$RANDOM_KEY`;
  }
  return `$KEY${Math.random().toString(36).substr(2, 7)}`
}
 
function typeKey(key) {
  return upperFirst(pluralize.singular(key));
}