|
1
|
import { Kind, parse, print, visit } from "graphql" |
|
2
|
|
|
3
|
export function cleanGraphQLSchema(schema: string): { |
|
4
|
schema: string |
|
5
|
notFound: Record<string, Record<string, string>> |
|
6
|
} { |
|
7
|
const extractTypeNameAndKind = (type) => { |
|
8
|
if (type.kind === Kind.NAMED_TYPE) { |
|
9
|
return [type.name.value, type.kind] |
|
10
|
} |
|
11
|
if (type.kind === Kind.NON_NULL_TYPE || type.kind === Kind.LIST_TYPE) { |
|
12
|
return extractTypeNameAndKind(type.type) |
|
13
|
} |
|
14
|
return [null, null] |
|
15
|
} |
|
16
|
|
|
17
|
const ast = parse(schema) |
|
18
|
|
|
19
|
const typeNames = new Set(["String", "Int", "Float", "Boolean", "ID"]) |
|
20
|
const extendedTypes = new Set() |
|
21
|
|
|
22
|
const kinds = [ |
|
23
|
Kind.OBJECT_TYPE_DEFINITION, |
|
24
|
Kind.INTERFACE_TYPE_DEFINITION, |
|
25
|
Kind.ENUM_TYPE_DEFINITION, |
|
26
|
Kind.SCALAR_TYPE_DEFINITION, |
|
27
|
Kind.INPUT_OBJECT_TYPE_DEFINITION, |
|
28
|
Kind.UNION_TYPE_DEFINITION, |
|
29
|
] |
|
30
|
ast.definitions.forEach((def: any) => { |
|
31
|
if (kinds.includes(def.kind)) { |
|
32
|
typeNames.add(def.name.value) |
|
33
|
} else if (def.kind === Kind.OBJECT_TYPE_EXTENSION) { |
|
34
|
extendedTypes.add(def.name.value) |
|
35
|
} |
|
36
|
}) |
|
37
|
|
|
38
|
const nonExistingMap: Record<string, Record<string, string>> = {} |
|
39
|
const parentStack: string[] = [] |
|
40
|
|
|
41
|
/* |
|
42
|
Traverse the graph mapping all the entities + fields and removing the ones that don't exist. |
|
43
|
Extensions are not removed, but marked with a "__extended" key if the main entity doesn't exist. (example: Link modules injecting fields into another module) |
|
44
|
*/ |
|
45
|
const cleanedAst = visit(ast, { |
|
46
|
ObjectTypeExtension: { |
|
47
|
enter(node) { |
|
48
|
const typeName = node.name.value |
|
49
|
|
|
50
|
parentStack.push(typeName) |
|
51
|
if (!typeNames.has(typeName)) { |
|
52
|
nonExistingMap[typeName] ??= {} |
|
53
|
nonExistingMap[typeName]["__extended"] = "" |
|
54
|
return null |
|
55
|
} |
|
56
|
return |
|
57
|
}, |
|
58
|
leave() { |
|
59
|
parentStack.pop() |
|
60
|
}, |
|
61
|
}, |
|
62
|
ObjectTypeDefinition: { |
|
63
|
enter(node) { |
|
64
|
parentStack.push(node.name.value) |
|
65
|
}, |
|
66
|
leave() { |
|
67
|
parentStack.pop() |
|
68
|
}, |
|
69
|
}, |
|
70
|
FieldDefinition: { |
|
71
|
leave(node) { |
|
72
|
const [typeName, kind] = extractTypeNameAndKind(node.type) |
|
73
|
|
|
74
|
if (!typeNames.has(typeName) && kind === Kind.NAMED_TYPE) { |
|
75
|
const currentParent = parentStack[parentStack.length - 1] |
|
76
|
|
|
77
|
nonExistingMap[currentParent] ??= {} |
|
78
|
nonExistingMap[currentParent][node.name.value] = typeName |
|
79
|
return null |
|
80
|
} |
|
81
|
return |
|
82
|
}, |
|
83
|
}, |
|
84
|
}) |
|
85
|
|
|
86
|
// Return the schema and the map of non existing entities and fields |
|
87
|
return { |
|
88
|
schema: print(cleanedAst), |
|
89
|
notFound: nonExistingMap, |
|
90
|
} |
|
91
|
} |