1 import type {
2 Event,
3 ICachingModuleService,
4 ICachingStrategy,
5 ModuleJoinerConfig,
6 } from "@medusajs/framework/types"
7 import {
8 type GraphQLSchema,
9 Modules,
10 toCamelCase,
11 upperCaseFirst,
12 } from "@medusajs/framework/utils"
13 import { type CachingModuleService } from "@services"
14 import type { InjectedDependencies } from "@types"
15 import stringify from "fast-json-stable-stringify"
16 import {
17 CacheInvalidationParser,
18 EntityReference,
19 InvalidationOperation,
20 } from "./parser"
21
22 export class DefaultCacheStrategy implements ICachingStrategy {
23 #cacheInvalidationParser: CacheInvalidationParser
24 #cacheModule: ICachingModuleService
25 #container: InjectedDependencies
26 #hasher: (data: string) => string
27
28 constructor(
29 container: InjectedDependencies,
30 cacheModule: CachingModuleService
31 ) {
32 this.#cacheModule = cacheModule
33 this.#container = container
34 this.#hasher = container.hasher
35 }
36
37 objectHash(input: any): string {
38 const str = stringify(input)
39 return this.#hasher(str)
40 }
41
42 async onApplicationStart(
43 schema: GraphQLSchema,
44 joinerConfigs: ModuleJoinerConfig[]
45 ) {
46 this.#cacheInvalidationParser = new CacheInvalidationParser(
47 schema,
48 joinerConfigs
49 )
50
51 const eventBus = this.#container[Modules.EVENT_BUS]
52
53 const handleEvent = async (data: Event) => {
54 try {
55 // We dont have to await anything here and the rest can be done in the background
56 return
57 } finally {
58 const eventName = data.name
59 const operation = eventName.split(".").pop() as InvalidationOperation
60 const entityType = eventName.split(".").slice(-2).shift()!
61
62 const eventData = data.data as
63 | { id: string | string[] }
64 | { id: string | string[] }[]
65
66 const normalizedEventData = Array.isArray(eventData)
67 ? eventData
68 : [eventData]
69
70 const tags: string[] = []
71 for (const item of normalizedEventData) {
72 const ids = Array.isArray(item.id) ? item.id : [item.id]
73
74 for (const id of ids) {
75 const entityReference: EntityReference = {
76 type: upperCaseFirst(toCamelCase(entityType)),
77 id,
78 }
79
80 const tags_ = await this.computeTags(item, {
81 entities: [entityReference],
82 operation,
83 })
84 tags.push(...tags_)
85 }
86 }
87
88 await this.#cacheModule.clear({
89 tags,
90 options: { autoInvalidate: true },
91 })
92 }
93 }
94
95 eventBus.subscribe("*", handleEvent)
96 eventBus.addInterceptor?.(handleEvent)
97 }
98
99 async computeKey(input: object) {
100 return this.objectHash(input)
101 }
102
103 async computeTags(
104 input: object,
105 options?: {
106 entities?: EntityReference[]
107 operation?: InvalidationOperation
108 }
109 ): Promise<string[]> {
110 // Parse the input object to identify entities
111 const entities_ =
112 options?.entities ||
113 this.#cacheInvalidationParser.parseObjectForEntities(input)
114
115 if (entities_.length === 0) {
116 return []
117 }
118
119 // Build invalidation events to get comprehensive cache keys
120 const events = this.#cacheInvalidationParser.buildInvalidationEvents(
121 entities_,
122 options?.operation
123 )
124
125 // Collect all unique cache keys from all events as tags
126 const tags = new Set<string>()
127
128 events.forEach((event) => {
129 event.cacheKeys.forEach((key) => tags.add(key))
130 })
131
132 return Array.from(tags)
133 }
134 }