1 import { MedusaModule } from "@medusajs/framework/modules-sdk"
2 import {
3 ModuleJoinerConfig,
4 ModuleJoinerRelationship,
5 } from "@medusajs/framework/types"
6 import {
7 camelToSnakeCase,
8 composeTableName,
9 isString,
10 lowerCaseFirst,
11 toPascalCase,
12 } from "@medusajs/framework/utils"
13
14 export function generateGraphQLSchema(
15 joinerConfig: ModuleJoinerConfig,
16 primary: ModuleJoinerRelationship,
17 foreign: ModuleJoinerRelationship,
18 { logger }: { logger } = { logger: console }
19 ) {
20 let fieldNames!: string[]
21 let entityName!: string
22
23 const isReadOnlyLink = joinerConfig.isReadOnlyLink
24 if (!isReadOnlyLink) {
25 fieldNames = primary.foreignKey.split(",").concat(foreign.foreignKey)
26
27 entityName = toPascalCase(
28 "Link_" +
29 (joinerConfig.databaseConfig?.tableName ??
30 composeTableName(
31 primary.serviceName,
32 primary.foreignKey,
33 foreign.serviceName,
34 foreign.foreignKey
35 ))
36 )
37 }
38
39 let typeDef = ""
40
41 for (const extend of joinerConfig.extends ?? []) {
42 const extendedModule = MedusaModule.getModuleInstance(extend.serviceName)
43 if (!extendedModule) {
44 throw new Error(
45 `Module ${extend.serviceName} not found. Please verify that the module is configured and installed, also the module must be loaded before the link modules.`
46 )
47 }
48
49 let extendedEntityName =
50 extendedModule[extend.serviceName].__joinerConfig.linkableKeys[
51 extend.relationship.primaryKey
52 ]
53
54 if (!isReadOnlyLink && (!primary || !foreign || !extendedEntityName)) {
55 logger.warn(
56 `Link modules schema: No linkable key found for ${extend.relationship.primaryKey} on module ${extend.serviceName}.`
57 )
58
59 continue
60 }
61
62 const fieldName = camelToSnakeCase(
63 lowerCaseFirst(extend.relationship.alias)
64 )
65
66 let type = extend.relationship.isList ? `[${entityName}]` : entityName
67 if (joinerConfig?.isReadOnlyLink) {
68 // TODO: In readonly links, the relationship of the extend where entity is undefined has to be applied on all entities in the module that have the relationshiop foreing key attribute (unkown in this context)
69 if (!extend.entity) {
70 continue
71 }
72
73 const rel = extend.relationship
74 const extendedService = MedusaModule.getModuleInstance(rel.serviceName)
75
76 const hasGraphqlSchema =
77 !!extendedService[rel.serviceName].__joinerConfig.schema
78 const relEntity = rel.entity
79 ? rel.entity
80 : extendedService[rel.serviceName].__joinerConfig.linkableKeys[
81 rel.primaryKey
82 ]
83
84 if (!relEntity || !hasGraphqlSchema) {
85 continue
86 }
87
88 type = rel.isList ? `[${relEntity}]` : relEntity!
89 extendedEntityName = extend.entity
90 }
91
92 /**
93 * Find the field aliases shortcut to extend the entity with it
94 */
95 const fieldsAliasesField = Object.entries(extend.fieldAlias || {})
96 .map(([field, config]) => {
97 const path = isString(config) ? config : config.path
98 const isList = isString(config)
99 ? extend.relationship.isList
100 : config.isList ?? extend.relationship.isList
101
102 const targetEntityAlias = path.split(".").pop()
103
104 const targetEntityRelation = joinerConfig.relationships?.find(
105 (relation) => relation.alias === targetEntityAlias
106 )
107
108 if (!targetEntityRelation) {
109 return
110 }
111
112 const targetEntityName = MedusaModule.getJoinerConfig(
113 targetEntityRelation.serviceName
114 ).linkableKeys?.[targetEntityRelation.foreignKey]
115
116 if (!targetEntityName) {
117 logger.warn(
118 `Link modules schema: No linkable key found for ${targetEntityRelation.foreignKey} on module ${targetEntityRelation.serviceName}.`
119 )
120
121 return
122 }
123
124 // TODO: Re visit field aliases that access properties from a type
125 /*const targetEntityType = `${targetEntityName}${
126 relationshipPropertyPath.length
127 ? relationshipPropertyPath.reduce((acc, value) => {
128 return `${acc}[${value}]`
129 }, targetEntityName)
130 : ""
131 }`*/
132
133 return `${field}: ${
134 isList ? `[${targetEntityName}]` : targetEntityName
135 }`
136 })
137 .filter(Boolean)
138
139 typeDef += `
140 extend type ${extendedEntityName} {
141 ${fieldName}: ${type}
142
143 ${fieldsAliasesField.join("\n")}
144 }
145 `
146 }
147
148 if (isReadOnlyLink) {
149 return typeDef
150 }
151
152 // Pivot table fields
153 const fields = fieldNames.reduce((acc, curr) => {
154 acc[curr] = {
155 type: "String",
156 nullable: false,
157 }
158 return acc
159 }, {})
160
161 const extraFields = joinerConfig.databaseConfig?.extraFields ?? {}
162
163 for (const column in extraFields) {
164 fields[column] = {
165 type: getGraphQLType(extraFields[column].type),
166 nullable: !!extraFields[column].nullable,
167 }
168 }
169
170 // TODO: temporary, every module might always expose their schema
171 const doesPrimaryExportSchema = !!MedusaModule.getJoinerConfig(
172 primary.serviceName
173 )?.schema
174 const doesForeignExportSchema = !!MedusaModule.getJoinerConfig(
175 foreign.serviceName
176 )?.schema
177
178 // Link table relationships
179 const primaryField = doesPrimaryExportSchema
180 ? `${camelToSnakeCase(primary.alias)}: ${toPascalCase(
181 primary.entity ?? composeTableName(primary.serviceName)
182 )}`
183 : ""
184
185 const foreignField = doesForeignExportSchema
186 ? `${camelToSnakeCase(foreign.alias)}: ${toPascalCase(
187 foreign.entity ?? composeTableName(foreign.serviceName)
188 )}`
189 : ""
190
191 typeDef += `
192 type ${entityName} {
193 ${(Object.entries(fields) as any)
194 .map(
195 ([field, { type, nullable }]) =>
196 `${field}: ${nullable ? type : `${type}!`}`
197 )
198 .join("\n ")}
199
200 ${primaryField}
201 ${foreignField}
202
203 createdAt: String!
204 updatedAt: String!
205 deletedAt: String
206 }
207 `
208
209 return typeDef
210 }
211
212 function getGraphQLType(type) {
213 const typeDef = {
214 numeric: "Float",
215 integer: "Int",
216 smallint: "Int",
217 tinyint: "Int",
218 mediumint: "Int",
219 float: "Float",
220 double: "Float",
221 boolean: "Boolean",
222 decimal: "Float",
223 string: "String",
224 uuid: "ID",
225 text: "String",
226 date: "Date",
227 time: "Time",
228 datetime: "DateTime",
229 bigint: "BigInt",
230 blob: "Blob",
231 uint8array: "[Int]",
232 array: "[String]",
233 enumArray: "[String]",
234 enum: "String",
235 json: "JSON",
236 jsonb: "JSON",
237 }
238
239 return typeDef[type] ?? "String"
240 }