values.js.flow 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // @flow strict
  2. import find from '../polyfills/find';
  3. import type { ObjMap } from '../jsutils/ObjMap';
  4. import keyMap from '../jsutils/keyMap';
  5. import inspect from '../jsutils/inspect';
  6. import printPathArray from '../jsutils/printPathArray';
  7. import { GraphQLError } from '../error/GraphQLError';
  8. import type {
  9. FieldNode,
  10. DirectiveNode,
  11. VariableDefinitionNode,
  12. } from '../language/ast';
  13. import { Kind } from '../language/kinds';
  14. import { print } from '../language/printer';
  15. import type { GraphQLSchema } from '../type/schema';
  16. import type { GraphQLField } from '../type/definition';
  17. import type { GraphQLDirective } from '../type/directives';
  18. import { isInputType, isNonNullType } from '../type/definition';
  19. import { typeFromAST } from '../utilities/typeFromAST';
  20. import { valueFromAST } from '../utilities/valueFromAST';
  21. import { coerceInputValue } from '../utilities/coerceInputValue';
  22. type CoercedVariableValues =
  23. | {| errors: $ReadOnlyArray<GraphQLError> |}
  24. | {| coerced: { [variable: string]: mixed, ... } |};
  25. /**
  26. * Prepares an object map of variableValues of the correct type based on the
  27. * provided variable definitions and arbitrary input. If the input cannot be
  28. * parsed to match the variable definitions, a GraphQLError will be thrown.
  29. *
  30. * Note: The returned value is a plain Object with a prototype, since it is
  31. * exposed to user code. Care should be taken to not pull values from the
  32. * Object prototype.
  33. *
  34. * @internal
  35. */
  36. export function getVariableValues(
  37. schema: GraphQLSchema,
  38. varDefNodes: $ReadOnlyArray<VariableDefinitionNode>,
  39. inputs: { +[variable: string]: mixed, ... },
  40. options?: {| maxErrors?: number |},
  41. ): CoercedVariableValues {
  42. const errors = [];
  43. const maxErrors = options?.maxErrors;
  44. try {
  45. const coerced = coerceVariableValues(
  46. schema,
  47. varDefNodes,
  48. inputs,
  49. (error) => {
  50. if (maxErrors != null && errors.length >= maxErrors) {
  51. throw new GraphQLError(
  52. 'Too many errors processing variables, error limit reached. Execution aborted.',
  53. );
  54. }
  55. errors.push(error);
  56. },
  57. );
  58. if (errors.length === 0) {
  59. return { coerced };
  60. }
  61. } catch (error) {
  62. errors.push(error);
  63. }
  64. return { errors };
  65. }
  66. function coerceVariableValues(
  67. schema: GraphQLSchema,
  68. varDefNodes: $ReadOnlyArray<VariableDefinitionNode>,
  69. inputs: { +[variable: string]: mixed, ... },
  70. onError: (GraphQLError) => void,
  71. ): { [variable: string]: mixed, ... } {
  72. const coercedValues = {};
  73. for (const varDefNode of varDefNodes) {
  74. const varName = varDefNode.variable.name.value;
  75. const varType = typeFromAST(schema, varDefNode.type);
  76. if (!isInputType(varType)) {
  77. // Must use input types for variables. This should be caught during
  78. // validation, however is checked again here for safety.
  79. const varTypeStr = print(varDefNode.type);
  80. onError(
  81. new GraphQLError(
  82. `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`,
  83. varDefNode.type,
  84. ),
  85. );
  86. continue;
  87. }
  88. if (!hasOwnProperty(inputs, varName)) {
  89. if (varDefNode.defaultValue) {
  90. coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);
  91. } else if (isNonNullType(varType)) {
  92. const varTypeStr = inspect(varType);
  93. onError(
  94. new GraphQLError(
  95. `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`,
  96. varDefNode,
  97. ),
  98. );
  99. }
  100. continue;
  101. }
  102. const value = inputs[varName];
  103. if (value === null && isNonNullType(varType)) {
  104. const varTypeStr = inspect(varType);
  105. onError(
  106. new GraphQLError(
  107. `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`,
  108. varDefNode,
  109. ),
  110. );
  111. continue;
  112. }
  113. coercedValues[varName] = coerceInputValue(
  114. value,
  115. varType,
  116. (path, invalidValue, error) => {
  117. let prefix =
  118. `Variable "$${varName}" got invalid value ` + inspect(invalidValue);
  119. if (path.length > 0) {
  120. prefix += ` at "${varName}${printPathArray(path)}"`;
  121. }
  122. onError(
  123. new GraphQLError(
  124. prefix + '; ' + error.message,
  125. varDefNode,
  126. undefined,
  127. undefined,
  128. undefined,
  129. error.originalError,
  130. ),
  131. );
  132. },
  133. );
  134. }
  135. return coercedValues;
  136. }
  137. /**
  138. * Prepares an object map of argument values given a list of argument
  139. * definitions and list of argument AST nodes.
  140. *
  141. * Note: The returned value is a plain Object with a prototype, since it is
  142. * exposed to user code. Care should be taken to not pull values from the
  143. * Object prototype.
  144. *
  145. * @internal
  146. */
  147. export function getArgumentValues(
  148. def: GraphQLField<mixed, mixed> | GraphQLDirective,
  149. node: FieldNode | DirectiveNode,
  150. variableValues?: ?ObjMap<mixed>,
  151. ): { [argument: string]: mixed, ... } {
  152. const coercedValues = {};
  153. // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
  154. const argumentNodes = node.arguments ?? [];
  155. const argNodeMap = keyMap(argumentNodes, (arg) => arg.name.value);
  156. for (const argDef of def.args) {
  157. const name = argDef.name;
  158. const argType = argDef.type;
  159. const argumentNode = argNodeMap[name];
  160. if (!argumentNode) {
  161. if (argDef.defaultValue !== undefined) {
  162. coercedValues[name] = argDef.defaultValue;
  163. } else if (isNonNullType(argType)) {
  164. throw new GraphQLError(
  165. `Argument "${name}" of required type "${inspect(argType)}" ` +
  166. 'was not provided.',
  167. node,
  168. );
  169. }
  170. continue;
  171. }
  172. const valueNode = argumentNode.value;
  173. let isNull = valueNode.kind === Kind.NULL;
  174. if (valueNode.kind === Kind.VARIABLE) {
  175. const variableName = valueNode.name.value;
  176. if (
  177. variableValues == null ||
  178. !hasOwnProperty(variableValues, variableName)
  179. ) {
  180. if (argDef.defaultValue !== undefined) {
  181. coercedValues[name] = argDef.defaultValue;
  182. } else if (isNonNullType(argType)) {
  183. throw new GraphQLError(
  184. `Argument "${name}" of required type "${inspect(argType)}" ` +
  185. `was provided the variable "$${variableName}" which was not provided a runtime value.`,
  186. valueNode,
  187. );
  188. }
  189. continue;
  190. }
  191. isNull = variableValues[variableName] == null;
  192. }
  193. if (isNull && isNonNullType(argType)) {
  194. throw new GraphQLError(
  195. `Argument "${name}" of non-null type "${inspect(argType)}" ` +
  196. 'must not be null.',
  197. valueNode,
  198. );
  199. }
  200. const coercedValue = valueFromAST(valueNode, argType, variableValues);
  201. if (coercedValue === undefined) {
  202. // Note: ValuesOfCorrectTypeRule validation should catch this before
  203. // execution. This is a runtime check to ensure execution does not
  204. // continue with an invalid argument value.
  205. throw new GraphQLError(
  206. `Argument "${name}" has invalid value ${print(valueNode)}.`,
  207. valueNode,
  208. );
  209. }
  210. coercedValues[name] = coercedValue;
  211. }
  212. return coercedValues;
  213. }
  214. /**
  215. * Prepares an object map of argument values given a directive definition
  216. * and a AST node which may contain directives. Optionally also accepts a map
  217. * of variable values.
  218. *
  219. * If the directive does not exist on the node, returns undefined.
  220. *
  221. * Note: The returned value is a plain Object with a prototype, since it is
  222. * exposed to user code. Care should be taken to not pull values from the
  223. * Object prototype.
  224. */
  225. export function getDirectiveValues(
  226. directiveDef: GraphQLDirective,
  227. node: { +directives?: $ReadOnlyArray<DirectiveNode>, ... },
  228. variableValues?: ?ObjMap<mixed>,
  229. ): void | { [argument: string]: mixed, ... } {
  230. const directiveNode =
  231. node.directives &&
  232. find(
  233. node.directives,
  234. (directive) => directive.name.value === directiveDef.name,
  235. );
  236. if (directiveNode) {
  237. return getArgumentValues(directiveDef, directiveNode, variableValues);
  238. }
  239. }
  240. function hasOwnProperty(obj: mixed, prop: string): boolean {
  241. return Object.prototype.hasOwnProperty.call(obj, prop);
  242. }