coerceValue.js.flow 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // @flow strict
  2. /* istanbul ignore file */
  3. import inspect from '../jsutils/inspect';
  4. import printPathArray from '../jsutils/printPathArray';
  5. import { type Path, pathToArray } from '../jsutils/Path';
  6. import { GraphQLError } from '../error/GraphQLError';
  7. import { type ASTNode } from '../language/ast';
  8. import { type GraphQLInputType } from '../type/definition';
  9. import { coerceInputValue } from './coerceInputValue';
  10. type CoercedValue = {|
  11. +errors: $ReadOnlyArray<GraphQLError> | void,
  12. +value: mixed,
  13. |};
  14. /**
  15. * Deprecated. Use coerceInputValue() directly for richer information.
  16. *
  17. * This function will be removed in v15
  18. */
  19. export function coerceValue(
  20. inputValue: mixed,
  21. type: GraphQLInputType,
  22. blameNode?: ASTNode,
  23. path?: Path,
  24. ): CoercedValue {
  25. const errors = [];
  26. const value = coerceInputValue(
  27. inputValue,
  28. type,
  29. (errorPath, invalidValue, error) => {
  30. let errorPrefix = 'Invalid value ' + inspect(invalidValue);
  31. const pathArray = [...pathToArray(path), ...errorPath];
  32. if (pathArray.length > 0) {
  33. errorPrefix += ` at "value${printPathArray(pathArray)}"`;
  34. }
  35. errors.push(
  36. new GraphQLError(
  37. errorPrefix + ': ' + error.message,
  38. blameNode,
  39. undefined,
  40. undefined,
  41. undefined,
  42. error.originalError,
  43. ),
  44. );
  45. },
  46. );
  47. return errors.length > 0
  48. ? { errors, value: undefined }
  49. : { errors: undefined, value };
  50. }