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