1 import { isListType, isNonNullType, isObjectType } from "graphql"
2
3 /**
4 * Extracts only the relation fields from the GraphQL type map.
5 * @param {Map<string, any>} typeMap - The GraphQL schema TypeMap.
6 * @returns {Map<string, Map<string, string>>} A map where each key is an entity name, and the values are a map of relation fields and their corresponding entity type.
7 */
8 export function extractRelationsFromGQL(
9 typeMap: Map<string, any>
10 ): Map<string, Map<string, string>> {
11 const relationMap = new Map()
12
13 // Extract the actual type
14 const getBaseType = (type) => {
15 if (isNonNullType(type) || isListType(type)) {
16 return getBaseType(type.ofType)
17 }
18 return type
19 }
20
21 for (const [typeName, graphqlType] of Object.entries(typeMap)) {
22 if (!isObjectType(graphqlType)) {
23 continue
24 }
25
26 const fields = graphqlType.getFields()
27 const entityRelations = new Map()
28
29 for (const [fieldName, fieldConfig] of Object.entries(fields)) {
30 const fieldType = getBaseType((fieldConfig as any).type)
31
32 // only add relation fields
33 if (isObjectType(fieldType)) {
34 entityRelations.set(fieldName, fieldType.name)
35 }
36 }
37 relationMap.set(typeName, entityRelations)
38 }
39
40 return relationMap
41 }