|
1
|
import { GraphQLNamedType, GraphQLObjectType, isObjectType } from "graphql" |
|
2
|
|
|
3
|
/** |
|
4
|
* Generate a list of fields and fields relations for a given type with the requested relations |
|
5
|
* @param schemaTypeMap |
|
6
|
* @param typeName |
|
7
|
* @param relations |
|
8
|
*/ |
|
9
|
export function gqlGetFieldsAndRelations( |
|
10
|
schemaTypeMap: { [key: string]: GraphQLNamedType }, |
|
11
|
typeName: string, |
|
12
|
relations: string[] = [] |
|
13
|
) { |
|
14
|
const result: string[] = [] |
|
15
|
|
|
16
|
function traverseFields(typeName, prefix = "") { |
|
17
|
const type = schemaTypeMap[typeName] |
|
18
|
|
|
19
|
if (!(type instanceof GraphQLObjectType)) { |
|
20
|
return |
|
21
|
} |
|
22
|
|
|
23
|
const fields = type.getFields() |
|
24
|
|
|
25
|
for (const fieldName in fields) { |
|
26
|
const field = fields[fieldName] |
|
27
|
let fieldType = field.type as any |
|
28
|
|
|
29
|
while (fieldType.ofType) { |
|
30
|
fieldType = fieldType.ofType |
|
31
|
} |
|
32
|
|
|
33
|
if (!isObjectType(fieldType)) { |
|
34
|
result.push(`${prefix}${fieldName}`) |
|
35
|
} else if (relations.includes(prefix + fieldName)) { |
|
36
|
traverseFields(fieldType.name, `${prefix}${fieldName}.`) |
|
37
|
} |
|
38
|
} |
|
39
|
} |
|
40
|
|
|
41
|
traverseFields(typeName) |
|
42
|
return result |
|
43
|
} |