1 import { ICacheService } from "@medusajs/framework/types"
2 import { Redis } from "ioredis"
3 import { RedisCacheModuleOptions } from "../types"
4
5 const DEFAULT_NAMESPACE = "medusa"
6 const DEFAULT_CACHE_TIME = 30 // 30 seconds
7 const EXPIRY_MODE = "EX" // "EX" stands for an expiry time in second
8
9 type InjectedDependencies = {
10 cacheRedisConnection: Redis
11 }
12
13 class RedisCacheService implements ICacheService {
14 protected readonly TTL: number
15 protected readonly redis: Redis
16 private readonly namespace: string
17
18 constructor(
19 { cacheRedisConnection }: InjectedDependencies,
20 options: RedisCacheModuleOptions = {}
21 ) {
22 this.redis = cacheRedisConnection
23 this.TTL = options.ttl ?? DEFAULT_CACHE_TIME
24 this.namespace = options.namespace || DEFAULT_NAMESPACE
25 }
26
27 __hooks = {
28 onApplicationShutdown: async () => {
29 this.redis.disconnect()
30 },
31 }
32
33 /**
34 * Set a key/value pair to the cache.
35 * If the ttl is 0 it will act like the value should not be cached at all.
36 * @param key
37 * @param data
38 * @param ttl
39 */
40 async set(
41 key: string,
42 data: Record<string, unknown>,
43 ttl: number = this.TTL
44 ): Promise<void> {
45 if (ttl === 0) {
46 return
47 }
48
49 await this.redis.set(
50 this.getCacheKey(key),
51 JSON.stringify(data),
52 EXPIRY_MODE,
53 ttl
54 )
55 }
56
57 /**
58 * Retrieve a cached value belonging to the given key.
59 * @param cacheKey
60 */
61 async get<T>(cacheKey: string): Promise<T | null> {
62 cacheKey = this.getCacheKey(cacheKey)
63 try {
64 const cached = await this.redis.get(cacheKey)
65 if (cached) {
66 return JSON.parse(cached)
67 }
68 } catch (err) {
69 await this.redis.unlink(cacheKey)
70 }
71 return null
72 }
73
74 /**
75 * Invalidate cache for a specific key. a key can be either a specific key or more global such as "ps:*".
76 * @param key
77 */
78 async invalidate(key: string): Promise<void> {
79 const pattern = this.getCacheKey(key)
80 let cursor = "0"
81 do {
82 const result = await this.redis.scan(
83 cursor,
84 "MATCH",
85 pattern,
86 "COUNT",
87 100
88 )
89 cursor = result[0]
90 const keys = result[1]
91
92 if (keys.length > 0) {
93 const deletePipeline = this.redis.pipeline()
94 for (const key of keys) {
95 deletePipeline.unlink(key)
96 }
97
98 await deletePipeline.exec()
99 }
100 } while (cursor !== "0")
101 }
102
103 /**
104 * Returns namespaced cache key
105 * @param key
106 */
107 private getCacheKey(key: string) {
108 return this.namespace ? `${this.namespace}:${key}` : key
109 }
110 }
111
112 export default RedisCacheService