-
Notifications
You must be signed in to change notification settings - Fork 18
/
+handler.ts
56 lines (48 loc) · 1.47 KB
/
+handler.ts
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
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';
import { createCache } from 'async-cache-dedupe';
import redisInstance from '~/utilities/redisInstance';
export default (async (app) => {
const cache = createCache({
ttl: 5,
storage: { type: 'redis', options: { client: redisInstance } },
});
const useCache = cache.define('redisText', async (id) => {
console.log('id =', id);
return { message: 'OK', id };
});
/*
```sh
# this will trigger the log: id = 1
$ curl --request GET --url http://127.0.0.1:3000/api/hello-world/caching-dedupe/1-redis
# response: { "message": "OK", "id": "1" }
# this won't trigger the log
$ curl --request GET --url http://127.0.0.1:3000/api/hello-world/caching-dedupe/1-redis
# response: { "message": "OK", "id": "1" }
# this will trigger the log: id = 2
$ curl --request GET --url http://127.0.0.1:3000/api/hello-world/caching-dedupe/2-redis
# response: { "message": "OK", "id": "2" }
```
*/
app.get(
'',
{
schema: {
params: Type.Object({
id: Type.String(),
}),
response: {
200: Type.Object({
message: Type.String(),
id: Type.String(),
}),
},
},
},
async (req, reply) => {
const { id } = req.params;
const cached = await useCache.redisText(id);
return reply.send(cached);
},
);
}) as FastifyPluginAsyncTypebox;