rustclan
rustclan2y ago

trying to cache api routes

Hello. I am using TRPC to make a site which integrates with a third party API. I need to add caching to some of my routes. I have tried to implement a temporary global cache, as seen below. In order to stop rate limits for the third party api.
// export API handler
export default createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === "query";
console.log(1);
if (ctx && allOk && isQuery) {
console.log(2);
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 15000;
return {
headers: {
"cache-control": `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});
// export API handler
export default createNextApiHandler({
router: appRouter,
createContext,
responseMeta({ ctx, paths, type, errors }) {
// checking that no procedures errored
const allOk = errors.length === 0;
// checking we're doing a query request
const isQuery = type === "query";
console.log(1);
if (ctx && allOk && isQuery) {
console.log(2);
// cache request for 1 day + revalidate once every second
const ONE_DAY_IN_SECONDS = 15000;
return {
headers: {
"cache-control": `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,
},
};
}
return {};
},
});
However, the cache-control header does not get changed, and nothing is cached. Mutiple requests are still made to the third party API. The cache code does run, as the console.log(2) appears in console. Any clue whats wrong?
3 Replies
rustclan
rustclan2y ago
bump
Alex / KATT 🐱
can you make a reproduction and post an issue? this should work and it has worked in the past, can't confirm or deny if this is a bug without testing it myself
rustclan
rustclan2y ago
yes, once I get some spare time i will try to make a reproduction.