/
get-fields-with-directives.ts
61 lines (49 loc) · 1.62 KB
/
get-fields-with-directives.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
import {
DocumentNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
InputObjectTypeDefinitionNode,
InputObjectTypeExtensionNode,
valueFromASTUntyped,
} from 'graphql';
import { DirectiveUsage } from './types.js';
export type TypeAndFieldToDirectives = {
[typeAndField: string]: DirectiveUsage[];
};
interface Options {
includeInputTypes?: boolean;
}
type SelectedNodes =
| ObjectTypeDefinitionNode
| ObjectTypeExtensionNode
| InputObjectTypeDefinitionNode
| InputObjectTypeExtensionNode;
export function getFieldsWithDirectives(documentNode: DocumentNode, options: Options = {}): TypeAndFieldToDirectives {
const result: TypeAndFieldToDirectives = {};
let selected = ['ObjectTypeDefinition', 'ObjectTypeExtension'];
if (options.includeInputTypes) {
selected = [...selected, 'InputObjectTypeDefinition', 'InputObjectTypeExtension'];
}
const allTypes = documentNode.definitions.filter(obj => selected.includes(obj.kind)) as SelectedNodes[];
for (const type of allTypes) {
const typeName = type.name.value;
if (type.fields == null) {
continue;
}
for (const field of type.fields) {
if (field.directives && field.directives.length > 0) {
const fieldName = field.name.value;
const key = `${typeName}.${fieldName}`;
const directives: DirectiveUsage[] = field.directives.map(d => ({
name: d.name.value,
args: (d.arguments || []).reduce(
(prev, arg) => ({ ...prev, [arg.name.value]: valueFromASTUntyped(arg.value) }),
{}
),
}));
result[key] = directives;
}
}
}
return result;
}