|
1
|
import { GraphQLNamedType, GraphQLObjectType, isObjectType } from "graphql" |
|
2
|
|
|
3
|
/** |
|
4
|
* From graphql schema get all the fields for the requested type and relations |
|
5
|
* |
|
6
|
* @param schemaTypeMap |
|
7
|
* @param typeName |
|
8
|
* @param relations |
|
9
|
* |
|
10
|
* @example |
|
11
|
* |
|
12
|
* const userModule = ` |
|
13
|
* type User { |
|
14
|
* id: ID! |
|
15
|
* name: String! |
|
16
|
* blabla: WHATEVER |
|
17
|
* } |
|
18
|
* |
|
19
|
* type Post { |
|
20
|
* author: User! |
|
21
|
* } |
|
22
|
* ` |
|
23
|
* |
|
24
|
* const postModule = ` |
|
25
|
* type Post { |
|
26
|
* id: ID! |
|
27
|
* title: String! |
|
28
|
* date: String |
|
29
|
* } |
|
30
|
* |
|
31
|
* type User { |
|
32
|
* posts: [Post!]! |
|
33
|
* } |
|
34
|
* |
|
35
|
* type WHATEVER { |
|
36
|
* random_field: String |
|
37
|
* post: Post |
|
38
|
* } |
|
39
|
* ` |
|
40
|
* |
|
41
|
* const mergedSchema = mergeTypeDefs([userModule, postModule]) |
|
42
|
* const schema = makeExecutableSchema({ |
|
43
|
* typeDefs: mergedSchema, |
|
44
|
* }) |
|
45
|
* |
|
46
|
* const fields = graphqlSchemaToFields(types, "User", ["posts"]) |
|
47
|
* |
|
48
|
* console.log(fields) |
|
49
|
* |
|
50
|
* // [ |
|
51
|
* // "id", |
|
52
|
* // "name", |
|
53
|
* // "posts.id", |
|
54
|
* // "posts.title", |
|
55
|
* // "posts.date", |
|
56
|
* // ] |
|
57
|
*/ |
|
58
|
export function graphqlSchemaToFields( |
|
59
|
schemaTypeMap: { [key: string]: GraphQLNamedType }, |
|
60
|
typeName: string, |
|
61
|
relations: string[] = [] |
|
62
|
) { |
|
63
|
const result: string[] = [] |
|
64
|
|
|
65
|
function traverseFields(typeName, parent = "") { |
|
66
|
const type = schemaTypeMap[typeName] |
|
67
|
|
|
68
|
if (!(type instanceof GraphQLObjectType)) { |
|
69
|
return |
|
70
|
} |
|
71
|
|
|
72
|
const fields = type.getFields() |
|
73
|
|
|
74
|
for (const fieldName in fields) { |
|
75
|
const field = fields[fieldName] |
|
76
|
let fieldType = field.type as any |
|
77
|
|
|
78
|
while (fieldType.ofType) { |
|
79
|
fieldType = fieldType.ofType |
|
80
|
} |
|
81
|
|
|
82
|
const composedField = parent ? `${parent}.${fieldName}` : fieldName |
|
83
|
if (!isObjectType(fieldType)) { |
|
84
|
result.push(composedField) |
|
85
|
} else if (relations.includes(composedField)) { |
|
86
|
traverseFields(fieldType.name, composedField) |
|
87
|
} |
|
88
|
} |
|
89
|
} |
|
90
|
|
|
91
|
traverseFields(typeName) |
|
92
|
return result |
|
93
|
} |