coerceInputValue.js.flow 5.37 KB
Newer Older
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
// @flow strict

import { forEach, isCollection } from 'iterall';

import objectValues from '../polyfills/objectValues';

import inspect from '../jsutils/inspect';
import invariant from '../jsutils/invariant';
import didYouMean from '../jsutils/didYouMean';
import isObjectLike from '../jsutils/isObjectLike';
import suggestionList from '../jsutils/suggestionList';
import printPathArray from '../jsutils/printPathArray';
import { type Path, addPath, pathToArray } from '../jsutils/Path';

import { GraphQLError } from '../error/GraphQLError';
import {
  type GraphQLInputType,
  isScalarType,
  isEnumType,
  isInputObjectType,
  isListType,
  isNonNullType,
} from '../type/definition';

type OnErrorCB = (
  path: $ReadOnlyArray<string | number>,
  invalidValue: mixed,
  error: GraphQLError,
) => void;

/**
 * Coerces a JavaScript value given a GraphQL Input Type.
 */
export function coerceInputValue(
  inputValue: mixed,
  type: GraphQLInputType,
  onError?: OnErrorCB = defaultOnError,
): mixed {
  return coerceInputValueImpl(inputValue, type, onError);
}

function defaultOnError(
  path: $ReadOnlyArray<string | number>,
  invalidValue: mixed,
  error: GraphQLError,
) {
  let errorPrefix = 'Invalid value ' + inspect(invalidValue);
  if (path.length > 0) {
    errorPrefix += ` at "value${printPathArray(path)}": `;
  }
  error.message = errorPrefix + ': ' + error.message;
  throw error;
}

function coerceInputValueImpl(
  inputValue: mixed,
  type: GraphQLInputType,
  onError: OnErrorCB,
  path: Path | void,
): mixed {
  if (isNonNullType(type)) {
    if (inputValue != null) {
      return coerceInputValueImpl(inputValue, type.ofType, onError, path);
    }
    onError(
      pathToArray(path),
      inputValue,
      new GraphQLError(
        `Expected non-nullable type ${inspect(type)} not to be null.`,
      ),
    );
    return;
  }

  if (inputValue == null) {
    // Explicitly return the value null.
    return null;
  }

  if (isListType(type)) {
    const itemType = type.ofType;
    if (isCollection(inputValue)) {
      const coercedValue = [];
      forEach((inputValue: any), (itemValue, index) => {
        coercedValue.push(
          coerceInputValueImpl(
            itemValue,
            itemType,
            onError,
            addPath(path, index),
          ),
        );
      });
      return coercedValue;
    }
    // Lists accept a non-list value as a list of one.
    return [coerceInputValueImpl(inputValue, itemType, onError, path)];
  }

  if (isInputObjectType(type)) {
    if (!isObjectLike(inputValue)) {
      onError(
        pathToArray(path),
        inputValue,
        new GraphQLError(`Expected type ${type.name} to be an object.`),
      );
      return;
    }

    const coercedValue = {};
    const fieldDefs = type.getFields();

    for (const field of objectValues(fieldDefs)) {
      const fieldValue = inputValue[field.name];

      if (fieldValue === undefined) {
        if (field.defaultValue !== undefined) {
          coercedValue[field.name] = field.defaultValue;
        } else if (isNonNullType(field.type)) {
          const typeStr = inspect(field.type);
          onError(
            pathToArray(path),
            inputValue,
            new GraphQLError(
              `Field ${field.name} of required type ${typeStr} was not provided.`,
            ),
          );
        }
        continue;
      }

      coercedValue[field.name] = coerceInputValueImpl(
        fieldValue,
        field.type,
        onError,
        addPath(path, field.name),
      );
    }

    // Ensure every provided field is defined.
    for (const fieldName of Object.keys(inputValue)) {
      if (!fieldDefs[fieldName]) {
        const suggestions = suggestionList(
          fieldName,
          Object.keys(type.getFields()),
        );
        onError(
          pathToArray(path),
          inputValue,
          new GraphQLError(
            `Field "${fieldName}" is not defined by type ${type.name}.` +
              didYouMean(suggestions),
          ),
        );
      }
    }
    return coercedValue;
  }

  if (isScalarType(type)) {
    let parseResult;

    // Scalars determine if a input value is valid via parseValue(), which can
    // throw to indicate failure. If it throws, maintain a reference to
    // the original error.
    try {
      parseResult = type.parseValue(inputValue);
    } catch (error) {
      onError(
        pathToArray(path),
        inputValue,
        new GraphQLError(
          `Expected type ${type.name}. ` + error.message,
          undefined,
          undefined,
          undefined,
          undefined,
          error,
        ),
      );
      return;
    }
    if (parseResult === undefined) {
      onError(
        pathToArray(path),
        inputValue,
        new GraphQLError(`Expected type ${type.name}.`),
      );
    }
    return parseResult;
  }

  if (isEnumType(type)) {
    if (typeof inputValue === 'string') {
      const enumValue = type.getValue(inputValue);
      if (enumValue) {
        return enumValue.value;
      }
    }
    const suggestions = suggestionList(
      String(inputValue),
      type.getValues().map(enumValue => enumValue.name),
    );
    onError(
      pathToArray(path),
      inputValue,
      new GraphQLError(`Expected type ${type.name}.` + didYouMean(suggestions)),
    );
    return;
  }

  // Not reachable. All possible input types have been considered.
  invariant(false, 'Unexpected input type: ' + inspect((type: empty)));
}