-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtest-cache.ts
More file actions
82 lines (71 loc) · 1.9 KB
/
test-cache.ts
File metadata and controls
82 lines (71 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { defineCachedFunction, defineCachedHandler } from 'nitro/cache';
import { defineHandler, getQuery } from 'nitro/h3';
const getCachedUser = defineCachedFunction(
async (userId: string) => {
return {
id: userId,
name: `User ${userId}`,
email: `user${userId}@example.com`,
timestamp: Date.now(),
};
},
{
maxAge: 60,
name: 'getCachedUser',
getKey: (userId: string) => `user:${userId}`,
},
);
const getCachedData = defineCachedFunction(
async (key: string) => {
return {
key,
value: `cached-value-${key}`,
timestamp: Date.now(),
};
},
{
maxAge: 120,
name: 'getCachedData',
getKey: (key: string) => `data:${key}`,
},
);
const cachedHandler = defineCachedHandler(
async event => {
return {
message: 'This response is cached',
timestamp: Date.now(),
path: event.path,
};
},
{
maxAge: 60,
name: 'cachedHandler',
},
);
export default defineHandler(async event => {
const results: Record<string, unknown> = {};
const testKey = String(getQuery(event).user ?? '123');
const dataKey = String(getQuery(event).data ?? 'test-key');
// cachedFunction - first call (cache miss)
const user1 = await getCachedUser(testKey);
results.cachedUser1 = user1;
// cachedFunction - second call (cache hit)
const user2 = await getCachedUser(testKey);
results.cachedUser2 = user2;
// cachedFunction with different key (cache miss)
const user3 = await getCachedUser(`${testKey}456`);
results.cachedUser3 = user3;
// another cachedFunction
const data1 = await getCachedData(dataKey);
results.cachedData1 = data1;
// cachedFunction - cache hit
const data2 = await getCachedData(dataKey);
results.cachedData2 = data2;
// cachedEventHandler
const cachedResponse = await cachedHandler(event);
results.cachedResponse = cachedResponse;
return {
success: true,
results,
};
});