You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: packages/document/main-doc/docs/en/guides/basic-features/data/data-cache.mdx
+127-1
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ sidebar_position: 4
4
4
---
5
5
# Data Caching
6
6
7
-
The `cache` function allows you to cache the results of data fetching or computation.
7
+
The `cache` function allows you to cache the results of data fetching or computation, Compared to full-page [rendering cache](/guides/basic-features/render/ssr-cache), it provides more fine-grained control over data granularity and is applicable to various scenarios such as Client-Side Rendering (CSR), Server-Side Rendering (SSR), and API services (BFF).
8
8
9
9
:::info
10
10
X.65.5 and above versions are required
@@ -34,6 +34,7 @@ const loader = async () => {
34
34
-`tag`: Tag to identify the cache, which can be used to invalidate the cache
35
35
-`maxAge`: Cache validity period (milliseconds)
36
36
-`revalidate`: Time window for revalidating the cache (milliseconds), similar to HTTP Cache-Control's stale-while-revalidate functionality
37
+
-`customKey`: Custom cache key function
37
38
38
39
The type of the `options` parameter is as follows:
39
40
@@ -42,6 +43,11 @@ interface CacheOptions {
42
43
tag?:string|string[];
43
44
maxAge?:number;
44
45
revalidate?:number;
46
+
customKey?: <Argsextendsany[]>(options: {
47
+
params:Args;
48
+
fn: (...args:Args) =>any;
49
+
generatedKey:string;
50
+
}) =>string|symbol;
45
51
}
46
52
```
47
53
@@ -153,6 +159,126 @@ revalidateTag('dashboard-stats'); // Invalidates the cache for both getDashboard
153
159
```
154
160
155
161
162
+
#### `customKey` parameter
163
+
164
+
The `customKey` parameter is used to customize the cache key. It is a function that receives an object with the following properties and returns a string or Symbol type as the cache key:
165
+
166
+
-`params`: Array of arguments passed to the cached function
167
+
-`fn`: Reference to the original function being cached
168
+
-`generatedKey`: Cache key automatically generated by the framework based on input parameters
169
+
170
+
This is very useful in some scenarios, such as when the function reference changes , but you want to still return the cached data.
171
+
172
+
```ts
173
+
import { cache } from'@modern-js/runtime/cache';
174
+
import { fetchUserData } from'./api';
175
+
176
+
// Different function references, but share the same cache via customKey
177
+
const getUserA =cache(
178
+
fetchUserData,
179
+
{
180
+
maxAge: CacheTime.MINUTE*5,
181
+
customKey: ({ params }) => {
182
+
// Return a stable string as the cache key
183
+
return`user-${params[0]}`;
184
+
},
185
+
}
186
+
);
187
+
188
+
// Even if the function reference changes,
189
+
// as long as customKey returns the same value, the cache will be hit
190
+
const getUserB =cache(
191
+
(...args) =>fetchUserData(...args), // New function reference
192
+
{
193
+
maxAge: CacheTime.MINUTE*5,
194
+
customKey: ({ params }) => {
195
+
// Return the same key as getUserA
196
+
return`user-${params[0]}`;
197
+
},
198
+
}
199
+
);
200
+
201
+
// You can also use Symbol as a cache key (usually used to share cache within the same application)
202
+
const USER_CACHE_KEY =Symbol('user-cache');
203
+
const getUserC =cache(
204
+
fetchUserData,
205
+
{
206
+
maxAge: CacheTime.MINUTE*5,
207
+
customKey: () =>USER_CACHE_KEY,
208
+
}
209
+
);
210
+
211
+
// You can utilize the generatedKey parameter to modify the default key
The `onCache` parameter allows you to track cache statistics such as hit rate. It's a callback function that receives information about each cache operation, including the status, key, parameters, and result.
console.log(`Cache ${status} for key: ${String(key)}`);
253
+
console.log(`Current hit rate: ${stats.hitRate() *100}%`);
254
+
}
255
+
}
256
+
);
257
+
258
+
// Usage example
259
+
awaitgetUser(1); // Cache miss
260
+
awaitgetUser(1); // Cache hit
261
+
awaitgetUser(2); // Cache miss
262
+
```
263
+
264
+
The `onCache` callback receives an object with the following properties:
265
+
266
+
-`status`: The cache operation status, which can be:
267
+
-`hit`: Cache hit, returning cached content
268
+
-`miss`: Cache miss, executing the function and caching the result
269
+
-`stale`: Cache hit but data is stale, returning cached content while revalidating in the background
270
+
-`key`: The cache key, which is either the result of `customKey` or the default generated key
271
+
-`params`: The parameters passed to the cached function
272
+
-`result`: The result data (either from cache or newly computed)
273
+
274
+
This callback is only invoked when the `options` parameter is provided. When using the cache function without options (for SSR request-scoped caching), the `onCache` callback is not called.
275
+
276
+
The `onCache` callback is useful for:
277
+
- Monitoring cache performance
278
+
- Calculating hit rates
279
+
- Logging cache operations
280
+
- Implementing custom metrics
281
+
156
282
### Storage
157
283
158
284
Currently, both client and server caches are stored in memory.
0 commit comments