-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b8c3b95
commit f437471
Showing
4 changed files
with
64 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
51 changes: 51 additions & 0 deletions
51
src/routes/hello-world/caching-dedupe/[id]-memory/+handler.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'; | ||
import { Type } from '@sinclair/typebox'; | ||
import { createCache } from 'async-cache-dedupe'; | ||
|
||
export default (async (app) => { | ||
const cache = createCache({ ttl: 5 }); | ||
|
||
const useCache = cache.define('memoryText', 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-memory | ||
* # 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-memory | ||
* # 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-memory | ||
* # 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.memoryText(id); | ||
|
||
return reply.send(cached); | ||
}, | ||
); | ||
}) as FastifyPluginAsyncTypebox; |