In-memory caching module for Medusa with TTL support and wildcard invalidation
npx @tessl/cli install tessl/npm-medusajs--cache-inmemory@2.10.00
# Medusa Cache In-memory
1
2
Medusa in-memory cache module provides a simple, Map-based cache store with TTL (time-to-live) functionality for the Medusa e-commerce framework. Designed for development and testing environments, it offers automatic expiration management and pattern-based cache invalidation.
3
4
## Package Information
5
6
- **Package Name**: @medusajs/cache-inmemory
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @medusajs/cache-inmemory`
10
- **Node.js**: >=20
11
12
## Core Imports
13
14
```typescript
15
import { initialize } from "@medusajs/cache-inmemory";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const { initialize } = require("@medusajs/cache-inmemory");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import { initialize } from "@medusajs/cache-inmemory";
28
29
// Initialize cache service with default 30-second TTL
30
const cache = await initialize({});
31
32
// Initialize cache service with custom TTL
33
const customCache = await initialize({ ttl: 60 });
34
35
// Basic operations
36
await cache.set("user:123", { name: "Alice", age: 30 });
37
const user = await cache.get("user:123"); // { name: "Alice", age: 30 }
38
39
// TTL-based expiration (data expires after TTL seconds)
40
await cache.set("temp:data", "temporary", 5); // expires in 5 seconds
41
42
// Pattern-based invalidation
43
await cache.set("products:electronics:1", { name: "Laptop" });
44
await cache.set("products:electronics:2", { name: "Phone" });
45
await cache.set("products:books:1", { name: "Novel" });
46
47
// Remove all electronics products
48
await cache.invalidate("products:electronics:*");
49
50
// Clear entire cache
51
await cache.clear();
52
```
53
54
## Architecture
55
56
The in-memory cache is built around these key components:
57
58
- **Map-based Storage**: Uses native JavaScript Map for efficient key-value storage
59
- **TTL Management**: Automatic expiration using Node.js timers with cleanup
60
- **Pattern Matching**: Wildcard support for bulk cache invalidation
61
- **Medusa Integration**: Implements ICacheService interface for framework compatibility
62
- **Memory Efficiency**: Automatic cleanup of expired entries and timeout references
63
64
## Capabilities
65
66
### Cache Storage and Retrieval
67
68
Core functionality for storing and retrieving cached data with automatic expiration.
69
70
```typescript { .api }
71
/**
72
* Main cache service class implementing ICacheService interface
73
*/
74
class InMemoryCacheService {
75
constructor(
76
deps: InjectedDependencies,
77
options?: InMemoryCacheModuleOptions
78
);
79
80
/**
81
* Retrieve data from the cache
82
* @param key - Cache key to retrieve
83
* @returns Promise resolving to cached data or null if not found/expired
84
*/
85
get<T>(key: string): Promise<T | null>;
86
87
/**
88
* Store data in the cache with optional TTL
89
* @param key - Cache key under which to store the data
90
* @param data - Data to be stored in the cache
91
* @param ttl - Time to live in seconds (defaults to configured TTL). If 0, operation is ignored.
92
*/
93
set<T>(key: string, data: T, ttl?: number): Promise<void>;
94
}
95
```
96
97
### Cache Invalidation
98
99
Remove specific cache entries or bulk invalidation using wildcard patterns.
100
101
```typescript { .api }
102
/**
103
* Delete data from the cache
104
* Supports wildcard (*) pattern matching for bulk operations
105
* @param key - Cache key or pattern (e.g., "user:*", "*:active")
106
*/
107
invalidate(key: string): Promise<void>;
108
109
/**
110
* Delete the entire cache
111
* Clears all stored data and timeout references
112
*/
113
clear(): Promise<void>;
114
```
115
116
### Module Initialization
117
118
Bootstrap the cache module within the Medusa framework.
119
120
```typescript { .api }
121
/**
122
* Initialize the cache module with optional configuration
123
* @param options - Module configuration options or external module declaration
124
* @returns Promise resolving to ICacheService instance
125
*/
126
function initialize(
127
options?: InMemoryCacheModuleOptions | ExternalModuleDeclaration
128
): Promise<ICacheService>;
129
```
130
131
## Types
132
133
```typescript { .api }
134
/**
135
* Configuration options for the in-memory cache module
136
*/
137
interface InMemoryCacheModuleOptions {
138
/** Time to keep data in cache (in seconds) */
139
ttl?: number;
140
}
141
142
/**
143
* Internal cache record structure
144
*/
145
interface CacheRecord<T> {
146
/** The cached data */
147
data: T;
148
/** Expiration timestamp in milliseconds */
149
expire: number;
150
}
151
152
/**
153
* Dependency injection container (empty for this module)
154
*/
155
type InjectedDependencies = {}
156
```
157
158
## Usage Examples
159
160
### Basic Caching
161
162
```typescript
163
import { initialize } from "@medusajs/cache-inmemory";
164
165
const cache = await initialize({ ttl: 300 }); // 5-minute TTL
166
167
// Store user data
168
await cache.set("user:alice", {
169
id: "alice",
170
name: "Alice Johnson",
171
preferences: { theme: "dark" }
172
});
173
174
// Retrieve user data
175
const user = await cache.get<User>("user:alice");
176
if (user) {
177
console.log(`Welcome back, ${user.name}!`);
178
}
179
```
180
181
### Custom TTL
182
183
```typescript
184
import { initialize } from "@medusajs/cache-inmemory";
185
186
const cache = await initialize({});
187
188
// Store temporary data with custom expiration
189
await cache.set("session:abc123", { userId: "alice" }, 3600); // 1 hour
190
await cache.set("rate-limit:api", { count: 1 }, 60); // 1 minute
191
```
192
193
### Pattern-based Invalidation
194
195
```typescript
196
import { initialize } from "@medusajs/cache-inmemory";
197
198
const cache = await initialize({});
199
200
// Store related data
201
await cache.set("products:category:electronics:1", laptop);
202
await cache.set("products:category:electronics:2", phone);
203
await cache.set("products:category:books:1", novel);
204
await cache.set("products:featured:electronics:1", laptop);
205
206
// Invalidate all electronics products
207
await cache.invalidate("products:category:electronics:*");
208
209
// Invalidate all featured items
210
await cache.invalidate("products:featured:*");
211
212
// Invalidate specific pattern
213
await cache.invalidate("products:*:electronics:*");
214
```
215
216
### Framework Integration
217
218
```typescript
219
import { initialize } from "@medusajs/cache-inmemory";
220
221
// Initialize as Medusa module
222
const cacheService = await initialize({
223
ttl: 600 // 10-minute default TTL
224
});
225
226
// Use in your Medusa service
227
class MyService {
228
constructor({ cacheService }) {
229
this.cache = cacheService;
230
}
231
232
async getCachedData(key: string) {
233
return await this.cache.get(key);
234
}
235
}
236
```
237
238
## Error Handling
239
240
The cache methods are designed to fail gracefully:
241
242
- `get()` returns `null` for non-existent or expired keys
243
- `set()` with TTL of 0 is ignored (no-op)
244
- `invalidate()` safely handles non-existent keys
245
- Pattern matching uses JavaScript RegExp, invalid patterns may throw
246
247
## Performance Considerations
248
249
- **Memory Usage**: All data is stored in memory; suitable for development/testing
250
- **TTL Cleanup**: Expired entries are cleaned up automatically via setTimeout
251
- **Pattern Matching**: Wildcard invalidation scans all keys; performance depends on total cache size
252
- **Production**: Recommended to use Redis-based cache module for production environments