UNPKG

1.49 kBPlain TextView Raw
1import {
2 typeFromAST,
3 GraphQLSchema,
4 DocumentNode,
5 NamedTypeNode,
6 GraphQLInputType,
7 GraphQLFloat,
8 Kind,
9} from 'graphql';
10
11export type VariableToType = {
12 [variable: string]: GraphQLInputType;
13};
14
15/**
16 * Generates a map of GraphQLInputTypes for
17 * all the variables in an AST document of operations
18 *
19 * @param schema
20 * @param documentAST
21 * @returns {VariableToType}
22 */
23export function collectVariables(
24 schema: GraphQLSchema,
25 documentAST: DocumentNode,
26): VariableToType {
27 const variableToType: VariableToType = Object.create(null);
28 // it would be more ideal to use visitWithTypeInfo here but it's very simple
29 documentAST.definitions.forEach(definition => {
30 if (definition.kind === 'OperationDefinition') {
31 const variableDefinitions = definition.variableDefinitions;
32 if (variableDefinitions) {
33 variableDefinitions.forEach(({ variable, type }) => {
34 const inputType = typeFromAST(
35 schema,
36 type as NamedTypeNode,
37 ) as GraphQLInputType;
38 if (inputType) {
39 variableToType[variable.name.value] = inputType;
40 } else if (type.kind === Kind.NAMED_TYPE) {
41 // in the experimental stream defer branch we are using, it seems typeFromAST() doesn't recognize Floats?
42 if (type.name.value === 'Float') {
43 variableToType[variable.name.value] = GraphQLFloat;
44 }
45 }
46 });
47 }
48 }
49 });
50 return variableToType;
51}