|
| 1 | +import { GraphQLError } from '../error/GraphQLError.js'; |
| 2 | + |
| 3 | +import { print } from '../language/printer.js'; |
| 4 | + |
| 5 | +import type { GraphQLInputType, GraphQLSchema } from '../type/index.js'; |
| 6 | +import { isInputType } from '../type/index.js'; |
| 7 | + |
| 8 | +import type { ConstValueNode, VariableDefinitionNode } from '../index.js'; |
| 9 | + |
| 10 | +import { typeFromAST } from './typeFromAST.js'; |
| 11 | +import { valueFromAST } from './valueFromAST.js'; |
| 12 | + |
| 13 | +/** |
| 14 | + * A GraphQLVariableSignature is required to coerce a variable value. |
| 15 | + * |
| 16 | + * @internal |
| 17 | + * */ |
| 18 | +export class GraphQLVariableSignature { |
| 19 | + name: string; |
| 20 | + type: GraphQLInputType; |
| 21 | + hasDefaultValue: boolean; |
| 22 | + _defaultValue: unknown; |
| 23 | + |
| 24 | + constructor( |
| 25 | + name: string, |
| 26 | + type: GraphQLInputType, |
| 27 | + defaultValueNode: ConstValueNode | undefined, |
| 28 | + ) { |
| 29 | + this.name = name; |
| 30 | + this.type = type; |
| 31 | + if (defaultValueNode) { |
| 32 | + this.hasDefaultValue = true; |
| 33 | + this._defaultValue = () => valueFromAST(defaultValueNode, type); |
| 34 | + } else { |
| 35 | + this.hasDefaultValue = false; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + getDefaultValue(): unknown { |
| 40 | + if (typeof this._defaultValue === 'function') { |
| 41 | + this._defaultValue = this._defaultValue(); |
| 42 | + } |
| 43 | + return this._defaultValue; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export function getVariableSignature( |
| 48 | + schema: GraphQLSchema, |
| 49 | + varDefNode: VariableDefinitionNode, |
| 50 | +): GraphQLVariableSignature | GraphQLError { |
| 51 | + const varName = varDefNode.variable.name.value; |
| 52 | + const varType = typeFromAST(schema, varDefNode.type); |
| 53 | + |
| 54 | + if (!isInputType(varType)) { |
| 55 | + // Must use input types for variables. This should be caught during |
| 56 | + // validation, however is checked again here for safety. |
| 57 | + const varTypeStr = print(varDefNode.type); |
| 58 | + return new GraphQLError( |
| 59 | + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, |
| 60 | + { nodes: varDefNode.type }, |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + return new GraphQLVariableSignature( |
| 65 | + varName, |
| 66 | + varType, |
| 67 | + varDefNode.defaultValue, |
| 68 | + ); |
| 69 | +} |
0 commit comments