1 import { ModuleJoinerConfig } from "@medusajs/framework/types"
2 import { isObject } from "@medusajs/framework/utils"
3 import {
4 GraphQLObjectType,
5 GraphQLSchema,
6 isListType,
7 isNonNullType,
8 isObjectType,
9 } from "graphql"
10
11 export interface EntityReference {
12 type: string
13 id: string | number
14 field?: string
15 isInArray?: boolean
16 }
17
18 export interface InvalidationEvent {
19 entityType: string
20 entityId: string | number
21 cacheKeys: string[]
22 }
23
24 /**
25 * The mutations a cached entity can go through. `attached`/`detached` are the
26 * link modules' equivalent of created/deleted, and `restored` reverses a soft
27 * delete.
28 */
29 export type InvalidationOperation =
30 | "created"
31 | "updated"
32 | "deleted"
33 | "restored"
34 | "attached"
35 | "detached"
36
37 const LIST_AFFECTING_OPERATIONS: InvalidationOperation[] = [
38 "created",
39 "updated",
40 "deleted",
41 "restored",
42 "attached",
43 "detached",
44 ]
45
46 export class CacheInvalidationParser {
47 private typeMap: Map<string, GraphQLObjectType>
48 private idPrefixToEntityName: Record<string, string>
49
50 constructor(schema: GraphQLSchema, joinerConfigs: ModuleJoinerConfig[]) {
51 this.typeMap = new Map()
52
53 // Build type map for quick lookups
54 const schemaTypeMap = schema.getTypeMap()
55 Object.keys(schemaTypeMap).forEach((typeName) => {
56 const type = schemaTypeMap[typeName]
57 if (isObjectType(type) && !typeName.startsWith("__")) {
58 this.typeMap.set(typeName, type)
59 }
60 })
61
62 this.idPrefixToEntityName = joinerConfigs.reduce((acc, joinerConfig) => {
63 if (joinerConfig.idPrefixToEntityName) {
64 Object.entries(joinerConfig.idPrefixToEntityName).forEach(
65 ([idPrefix, entityName]) => {
66 acc[idPrefix] = entityName
67 }
68 )
69 }
70 return acc
71 }, {} as Record<string, string>)
72 }
73
74 /**
75 * Parse an object to identify entities and their relationships
76 */
77 parseObjectForEntities(
78 obj: any,
79 parentType?: string,
80 isInArray: boolean = false
81 ): EntityReference[] {
82 const entities: EntityReference[] = []
83
84 if (!obj || typeof obj !== "object") {
85 return entities
86 }
87
88 // Check if this object matches any known GraphQL types
89 const detectedType = this.detectEntityType(obj, parentType)
90 if (detectedType && obj.id) {
91 entities.push({
92 type: detectedType,
93 id: obj.id,
94 isInArray,
95 })
96 }
97
98 // Recursively parse nested objects and arrays
99 Object.keys(obj).forEach((key) => {
100 const value = obj[key]
101
102 if (Array.isArray(value)) {
103 value.forEach((item) => {
104 entities.push(
105 ...this.parseObjectForEntities(
106 item,
107 this.getRelationshipType(detectedType, key),
108 true
109 )
110 )
111 })
112 } else if (isObject(value)) {
113 entities.push(
114 ...this.parseObjectForEntities(
115 value,
116 this.getRelationshipType(detectedType, key),
117 false
118 )
119 )
120 }
121 })
122
123 return entities
124 }
125
126 /**
127 * Detect entity type based on object structure and GraphQL type map
128 */
129 private detectEntityType(obj: any, suggestedType?: string): string | null {
130 if (obj.id) {
131 const idParts = obj.id.split("_")
132 if (idParts.length > 1 && this.idPrefixToEntityName[idParts[0]]) {
133 return this.idPrefixToEntityName[idParts[0]]
134 }
135 }
136
137 if (suggestedType && this.typeMap.has(suggestedType)) {
138 const type = this.typeMap.get(suggestedType)!
139 if (this.objectMatchesType(obj, type)) {
140 return suggestedType
141 }
142 }
143
144 // Try to match against all known types
145 for (const [typeName, type] of this.typeMap) {
146 if (this.objectMatchesType(obj, type)) {
147 return typeName
148 }
149 }
150
151 return null
152 }
153
154 /**
155 * Check if object structure matches GraphQL type fields
156 */
157 private objectMatchesType(obj: any, type: GraphQLObjectType): boolean {
158 const fields = type.getFields()
159 const objKeys = Object.keys(obj)
160
161 // Must have id field for entities
162 if (!obj.id || !fields.id) {
163 return false
164 }
165
166 // Check if at least 50% of non-null object fields match type fields
167 const matchingFields = objKeys.filter((key) => fields[key]).length
168 return matchingFields >= Math.max(1, objKeys.length * 0.5)
169 }
170
171 /**
172 * Get the expected type for a relationship field
173 */
174 private getRelationshipType(
175 parentType: string | null,
176 fieldName: string
177 ): string | undefined {
178 if (!parentType || !this.typeMap.has(parentType)) {
179 return undefined
180 }
181
182 const type = this.typeMap.get(parentType)!
183 const field = type.getFields()[fieldName]
184
185 if (!field) {
186 return undefined
187 }
188
189 let fieldType = field.type
190
191 // Unwrap NonNull and List wrappers
192 if (isNonNullType(fieldType)) {
193 fieldType = fieldType.ofType
194 }
195 if (isListType(fieldType)) {
196 fieldType = fieldType.ofType
197 }
198 if (isNonNullType(fieldType)) {
199 fieldType = fieldType.ofType
200 }
201
202 if (isObjectType(fieldType)) {
203 return fieldType.name
204 }
205
206 return undefined
207 }
208
209 /**
210 * Build invalidation events based on parsed entities
211 */
212 buildInvalidationEvents(
213 entities: EntityReference[],
214 operation: InvalidationOperation = "updated"
215 ): InvalidationEvent[] {
216 const events: InvalidationEvent[] = []
217 const processedEntities = new Set<string>()
218
219 entities.forEach((entity) => {
220 const entityKey = `${entity.type}:${entity.id}`
221
222 if (processedEntities.has(entityKey)) {
223 return
224 }
225 processedEntities.add(entityKey)
226
227 const affectedKeys = this.buildAffectedCacheKeys(entity, operation)
228
229 events.push({
230 entityType: entity.type,
231 entityId: entity.id,
232 cacheKeys: affectedKeys,
233 })
234 })
235
236 return events
237 }
238
239 /**
240 * Build list of cache keys that should be invalidated
241 */
242 private buildAffectedCacheKeys(
243 entity: EntityReference,
244 operation: InvalidationOperation = "updated"
245 ): string[] {
246 const keys = new Set<string>()
247
248 keys.add(`${entity.type}:${entity.id}`)
249
250 // Add the list key when the entity was found in an array context or for any
251 // mutating operation. Updates are included because a mutation can change
252 // whether an entity matches a cached list's filters (e.g. a product going
253 // from draft to published), and the cache layer has no way of knowing which
254 // fields are filter-relevant. Attach/detach are included because a link row
255 // never carries a usable id at attach time, so the list key is the only tag
256 // a cached link query can be invalidated by. Restore is included because the
257 // entity re-enters every list it was soft deleted out of.
258 if (entity.isInArray || LIST_AFFECTING_OPERATIONS.includes(operation)) {
259 keys.add(`${entity.type}:list:*`)
260 }
261
262 return Array.from(keys)
263 }
264 }