Mirror: The spec-compliant minimum of client-side GraphQL.
1import type { TypeNode, ValueNode } from './ast'; 2import type { Maybe } from './types'; 3 4export function valueFromASTUntyped( 5 node: ValueNode, 6 variables?: Maybe<Record<string, any>> 7): unknown { 8 switch (node.kind) { 9 case 'NullValue': 10 return null; 11 case 'IntValue': 12 return parseInt(node.value, 10); 13 case 'FloatValue': 14 return parseFloat(node.value); 15 case 'StringValue': 16 case 'EnumValue': 17 case 'BooleanValue': 18 return node.value; 19 case 'ListValue': { 20 const values: unknown[] = []; 21 for (const value of node.values) values.push(valueFromASTUntyped(value, variables)); 22 return values; 23 } 24 case 'ObjectValue': { 25 const obj = Object.create(null); 26 for (const field of node.fields) 27 obj[field.name.value] = valueFromASTUntyped(field.value, variables); 28 return obj; 29 } 30 case 'Variable': 31 return variables && variables[node.name.value]; 32 } 33} 34 35export function valueFromTypeNode( 36 node: ValueNode, 37 type: TypeNode, 38 variables?: Maybe<Record<string, any>> 39): unknown { 40 if (node.kind === 'Variable') { 41 const variableName = node.name.value; 42 return variables ? valueFromTypeNode(variables[variableName], type, variables) : undefined; 43 } else if (type.kind === 'NonNullType') { 44 return node.kind !== 'NullValue' ? valueFromTypeNode(node, type, variables) : undefined; 45 } else if (node.kind === 'NullValue') { 46 return null; 47 } else if (type.kind === 'ListType') { 48 if (node.kind === 'ListValue') { 49 const values: unknown[] = []; 50 for (const value of node.values) { 51 const coerced = valueFromTypeNode(value, type.type, variables); 52 if (coerced === undefined) { 53 return undefined; 54 } else { 55 values.push(coerced); 56 } 57 } 58 return values; 59 } 60 } else if (type.kind === 'NamedType') { 61 switch (type.name.value) { 62 case 'Int': 63 case 'Float': 64 case 'String': 65 case 'Bool': 66 return type.name.value + 'Value' === node.kind 67 ? valueFromASTUntyped(node, variables) 68 : undefined; 69 default: 70 return valueFromASTUntyped(node, variables); 71 } 72 } 73}