-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathindex.ts
375 lines (356 loc) · 10.7 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import * as assert from "assert";
import {
getNamedType,
isCompositeType,
GraphQLObjectType,
GraphQLUnionType,
GraphQLResolveInfo,
GraphQLField,
GraphQLCompositeType,
GraphQLInterfaceType,
GraphQLType,
GraphQLNamedType,
ASTNode,
FieldNode,
SelectionNode,
FragmentSpreadNode,
InlineFragmentNode,
NamedTypeNode,
} from "graphql";
import { getArgumentValues } from "graphql/execution/values";
import * as debugFactory from "debug";
type mixed = Record<string, any> | string | number | boolean | undefined | null;
export interface FieldsByTypeName {
[str: string]: {
[str: string]: ResolveTree;
};
}
export interface ResolveTree {
name: string;
alias: string;
args: {
[str: string]: mixed;
};
fieldsByTypeName: FieldsByTypeName;
}
const debug = debugFactory("graphql-parse-resolve-info");
const DEBUG_ENABLED = debug.enabled;
function getArgVal(resolveInfo: GraphQLResolveInfo, argument: any) {
if (argument.kind === "Variable") {
return resolveInfo.variableValues[argument.name.value];
} else if (argument.kind === "BooleanValue") {
return argument.value;
}
}
function argNameIsIf(arg: any): boolean {
return arg && arg.name ? arg.name.value === "if" : false;
}
function skipField(
resolveInfo: GraphQLResolveInfo,
{ directives = [] }: SelectionNode
) {
let skip = false;
directives.forEach(directive => {
const directiveName = directive.name.value;
if (Array.isArray(directive.arguments)) {
const ifArgumentAst = directive.arguments.find(argNameIsIf);
if (ifArgumentAst) {
const argumentValueAst = ifArgumentAst.value;
if (directiveName === "skip") {
skip = skip || getArgVal(resolveInfo, argumentValueAst);
} else if (directiveName === "include") {
skip = skip || !getArgVal(resolveInfo, argumentValueAst);
}
}
}
});
return skip;
}
// Originally based on https://github.com/tjmehta/graphql-parse-fields
export function getAliasFromResolveInfo(
resolveInfo: GraphQLResolveInfo
): string {
const asts: ReadonlyArray<FieldNode> =
// @ts-ignore Property 'fieldASTs' does not exist on type 'GraphQLResolveInfo'.
resolveInfo.fieldNodes || resolveInfo.fieldASTs;
for (let i = 0, l = asts.length; i < l; i++) {
const val = asts[i];
if (val.kind === "Field") {
const alias = val.alias ? val.alias.value : val.name && val.name.value;
if (alias) {
return alias;
}
}
}
throw new Error("Could not determine alias?!");
}
export interface ParseOptions {
keepRoot?: boolean;
deep?: boolean;
}
export function parseResolveInfo(
resolveInfo: GraphQLResolveInfo,
options: ParseOptions = {}
): ResolveTree | FieldsByTypeName | null | undefined {
const fieldNodes: ReadonlyArray<FieldNode> =
// @ts-ignore Property 'fieldASTs' does not exist on type 'GraphQLResolveInfo'.
resolveInfo.fieldNodes || resolveInfo.fieldASTs;
const { parentType } = resolveInfo;
if (!fieldNodes) {
throw new Error("No fieldNodes provided!");
}
if (options.keepRoot == null) {
options.keepRoot = false;
}
if (options.deep == null) {
options.deep = true;
}
const tree = fieldTreeFromAST(
fieldNodes,
resolveInfo,
undefined,
options,
parentType
);
if (!options.keepRoot) {
const typeKey = firstKey(tree);
if (!typeKey) {
return null;
}
const fields = tree[typeKey];
const fieldKey = firstKey(fields);
if (!fieldKey) {
return null;
}
return fields[fieldKey];
}
return tree;
}
function getFieldFromAST<TContext>(
ast: ASTNode,
parentType: GraphQLCompositeType
): GraphQLField<GraphQLCompositeType, TContext> | undefined {
if (ast.kind === "Field") {
const fieldNode: FieldNode = ast;
const fieldName = fieldNode.name.value;
if (!(parentType instanceof GraphQLUnionType)) {
const type: GraphQLObjectType | GraphQLInterfaceType = parentType;
return type.getFields()[fieldName];
} else {
// XXX: TODO: Handle GraphQLUnionType
}
}
return undefined;
}
let iNum = 1;
function fieldTreeFromAST<T extends SelectionNode>(
inASTs: ReadonlyArray<T> | T,
resolveInfo: GraphQLResolveInfo,
initTree: FieldsByTypeName = {},
options: ParseOptions = {},
parentType: GraphQLCompositeType,
depth = ""
): FieldsByTypeName {
const instance = iNum++;
if (DEBUG_ENABLED)
debug(
"%s[%d] Entering fieldTreeFromAST with parent type '%s'",
depth,
instance,
parentType
);
const { variableValues } = resolveInfo;
const fragments = resolveInfo.fragments || {};
const asts: ReadonlyArray<T> = Array.isArray(inASTs) ? inASTs : [inASTs];
if (!initTree[parentType.name]) {
initTree[parentType.name] = {};
}
const outerDepth = depth;
return asts.reduce((tree, selectionVal: SelectionNode, idx) => {
const depth = DEBUG_ENABLED ? `${outerDepth} ` : null;
if (DEBUG_ENABLED)
debug(
"%s[%d] Processing AST %d of %d; kind = %s",
depth,
instance,
idx + 1,
asts.length,
selectionVal.kind
);
if (skipField(resolveInfo, selectionVal)) {
if (DEBUG_ENABLED)
debug("%s[%d] IGNORING due to directive", depth, instance);
} else if (selectionVal.kind === "Field") {
const val: FieldNode = selectionVal;
const name = val.name.value;
const isReserved = name[0] === "_" && name[1] === "_" && name !== "__id";
if (isReserved) {
if (DEBUG_ENABLED)
debug(
"%s[%d] IGNORING because field '%s' is reserved",
depth,
instance,
name
);
} else {
const alias: string =
val.alias && val.alias.value ? val.alias.value : name;
if (DEBUG_ENABLED)
debug(
"%s[%d] Field '%s' (alias = '%s')",
depth,
instance,
name,
alias
);
const field = getFieldFromAST(val, parentType);
if (field == null) {
return tree;
}
const fieldGqlTypeOrUndefined = getNamedType(field.type);
if (!fieldGqlTypeOrUndefined) {
return tree;
}
const fieldGqlType: GraphQLNamedType = fieldGqlTypeOrUndefined;
const args = getArgumentValues(field, val, variableValues) || {};
if (parentType.name && !tree[parentType.name][alias]) {
const newTreeRoot: ResolveTree = {
name,
alias,
args,
fieldsByTypeName: isCompositeType(fieldGqlType)
? {
[fieldGqlType.name]: {},
}
: {},
};
tree[parentType.name][alias] = newTreeRoot;
}
const selectionSet = val.selectionSet;
if (
selectionSet != null &&
options.deep &&
isCompositeType(fieldGqlType)
) {
const newParentType: GraphQLCompositeType = fieldGqlType;
if (DEBUG_ENABLED)
debug("%s[%d] Recursing into subfields", depth, instance);
fieldTreeFromAST(
selectionSet.selections,
resolveInfo,
tree[parentType.name][alias].fieldsByTypeName,
options,
newParentType,
`${depth} `
);
} else {
// No fields to add
if (DEBUG_ENABLED)
debug("%s[%d] Exiting (no fields to add)", depth, instance);
}
}
} else if (selectionVal.kind === "FragmentSpread" && options.deep) {
const val: FragmentSpreadNode = selectionVal;
const name = val.name && val.name.value;
if (DEBUG_ENABLED)
debug("%s[%d] Fragment spread '%s'", depth, instance, name);
const fragment = fragments[name];
assert(fragment, 'unknown fragment "' + name + '"');
let fragmentType: GraphQLNamedType | null | undefined = parentType;
if (fragment.typeCondition) {
fragmentType = getType(resolveInfo, fragment.typeCondition);
}
if (fragmentType && isCompositeType(fragmentType)) {
const newParentType: GraphQLCompositeType = fragmentType;
fieldTreeFromAST(
fragment.selectionSet.selections,
resolveInfo,
tree,
options,
newParentType,
`${depth} `
);
}
} else if (selectionVal.kind === "InlineFragment" && options.deep) {
const val: InlineFragmentNode = selectionVal;
const fragment = val;
let fragmentType: GraphQLNamedType | null | undefined = parentType;
if (fragment.typeCondition) {
fragmentType = getType(resolveInfo, fragment.typeCondition);
}
if (DEBUG_ENABLED)
debug(
"%s[%d] Inline fragment (parent = '%s', type = '%s')",
depth,
instance,
parentType,
fragmentType
);
if (fragmentType && isCompositeType(fragmentType)) {
const newParentType: GraphQLCompositeType = fragmentType;
fieldTreeFromAST(
fragment.selectionSet.selections,
resolveInfo,
tree,
options,
newParentType,
`${depth} `
);
}
} else {
if (DEBUG_ENABLED)
debug(
"%s[%d] IGNORING because kind '%s' not understood",
depth,
instance,
selectionVal.kind
);
}
// Ref: https://github.com/graphile/postgraphile/pull/342/files#diff-d6702ec9fed755c88b9d70b430fda4d8R148
return tree;
}, initTree);
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function firstKey(obj: Record<string, unknown>) {
for (const key in obj) {
if (hasOwnProperty.call(obj, key)) {
return key;
}
}
}
function getType(
resolveInfo: GraphQLResolveInfo,
typeCondition: NamedTypeNode
) {
const { schema } = resolveInfo;
const { kind, name } = typeCondition;
if (kind === "NamedType") {
const typeName = name.value;
return schema.getType(typeName);
}
}
export function simplifyParsedResolveInfoFragmentWithType(
parsedResolveInfoFragment: ResolveTree,
type: GraphQLType
) {
const { fieldsByTypeName } = parsedResolveInfoFragment;
const fields = {};
const strippedType = getNamedType(type);
if (isCompositeType(strippedType)) {
Object.assign(fields, fieldsByTypeName[strippedType.name]);
if (strippedType instanceof GraphQLObjectType) {
const objectType: GraphQLObjectType = strippedType;
// GraphQL ensures that the subfields cannot clash, so it's safe to simply overwrite them
for (const anInterface of objectType.getInterfaces()) {
Object.assign(fields, fieldsByTypeName[anInterface.name]);
}
}
}
return {
...parsedResolveInfoFragment,
fields,
};
}
export const parse = parseResolveInfo;
export const simplify = simplifyParsedResolveInfoFragmentWithType;
export const getAlias = getAliasFromResolveInfo;