-
-
Notifications
You must be signed in to change notification settings - Fork 454
/
variables.ts
72 lines (62 loc) · 1.83 KB
/
variables.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {
FieldNode,
OperationDefinitionNode,
valueFromASTUntyped,
} from 'graphql';
import { getName } from './node';
import { Variables } from '../types';
/** Evaluates a fields arguments taking vars into account */
export const getFieldArguments = (
node: FieldNode,
vars: Variables
): null | Variables => {
let args: null | Variables = null;
if (node.arguments) {
for (let i = 0, l = node.arguments.length; i < l; i++) {
const arg = node.arguments[i];
const value = valueFromASTUntyped(arg.value, vars);
if (value !== undefined && value !== null) {
if (!args) args = {};
args[getName(arg)] = value as any;
}
}
}
return args;
};
/** Returns a filtered form of variables with values missing that the query doesn't require */
export const filterVariables = (
node: OperationDefinitionNode,
input: void | object
) => {
if (!input || !node.variableDefinitions) {
return undefined;
}
const vars = {};
for (let i = 0, l = node.variableDefinitions.length; i < l; i++) {
const name = getName(node.variableDefinitions[i].variable);
vars[name] = input[name];
}
return vars;
};
/** Returns a normalized form of variables with defaulted values */
export const normalizeVariables = (
node: OperationDefinitionNode,
input: void | Record<string, unknown>
): Variables => {
const vars = {};
if (!input) return vars;
if (node.variableDefinitions) {
for (let i = 0, l = node.variableDefinitions.length; i < l; i++) {
const def = node.variableDefinitions[i];
const name = getName(def.variable);
vars[name] =
input[name] === undefined && def.defaultValue
? valueFromASTUntyped(def.defaultValue, input)
: input[name];
}
}
for (const key in input) {
if (!(key in vars)) vars[key] = input[key];
}
return vars;
};