Closed 5t111111 closed 1 month ago
In my situation, the issue was resolved by explicitly using the useAwait
option. I believe the problem was likely caused by the callback function of cache.set
not being designed to work with async
/ await
, so I think my usage was incorrect.
Below is the updated code:
import Fastify from "fastify";
import fastifyCaching from "@fastify/caching";
import abstractCache from "abstract-cache";
const fastify = Fastify({
logger: true,
});
const abcache = abstractCache({
useAwait: true,
});
fastify.register(fastifyCaching, {
privacy: fastifyCaching.privacy.PRIVATE,
cache: abcache,
});
fastify.get("/", async function (request, reply) {
const extData = await fastify.cache.get("extData");
if (extData) {
return reply.send(extData.item);
}
const externalApiResponse = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
const externalApiResponseJson = await externalApiResponse.json();
fastify.cache.set("extData", externalApiResponseJson, 10000);
reply.send(externalApiResponseJson);
});
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});
Prerequisites
Issue
Sorry, I'm not sure if this is a bug or if I'm using it incorrectly.
I am trying to use fastify-caching to cache the results of a process that fetches data from an external API within a route handler.
The mechanism is simple:
To achieve this, I tried to implement caching by nesting
cache.get
andcache.set
callbacks, as shown below. However, I always get aReply was already sent
error when there is no cached data. Also, the response being sent is not theexternalApiResponseJson
, but an empty response.This code is also a minimal reproduction of the issue, and the actual project involves more complex processing, but the basic structure remains the same.
I looked through the documentation and test codes of fastify-caching, but I could not find an example that uses
cache.get
andcache.set
within the same route handler, so I am unsure of the correct usage. I would appreciate any guidance.Node version: 20.18.0
package.json