Use previous cached value on cached functions #3696
Unanswered
pabloraissiguier
asked this question in
Q&A
Replies: 1 comment
-
Accessing Previous Cache Value in NitroCurrently there is no built-in way to get the previous value in the cache handler. Here are workarounds: Option 1: Manual cache check before updateimport { useStorage } from "#imports";
export default defineCachedFunction(async (id: string) => {
const storage = useStorage("cache");
const cacheKey = `nitro:functions:myFunc:${id}`;
// Get previous value
const previous = await storage.getItem(cacheKey);
// Fetch new data
const newData = await fetchFromAPI(id);
// Compare or validate
if (previous && shouldKeepPrevious(previous, newData)) {
return previous.value;
}
return newData;
}, {
maxAge: 60 * 10,
swr: true,
});Option 2: Wrapper with historyconst withPrevious = (fn, options) => {
const cache = new Map();
return defineCachedFunction(async (...args) => {
const key = JSON.stringify(args);
const previous = cache.get(key);
const result = await fn(...args, { previous });
cache.set(key, result);
return result;
}, options);
};
// Usage
export default withPrevious(async (id, { previous }) => {
const newData = await fetchAPI(id);
if (previous && newData.version === previous.version) {
return previous; // Keep old if unchanged
}
return newData;
}, { maxAge: 600 });Feature RequestThis would be a useful addition. Consider opening a feature request for something like: defineCachedFunction(async (id, { previousValue }) => {
// previousValue available here
}, { swr: true }); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi community!
I'm working on a nuxt app and using Nitro cached functions for some tasks that require an external api. I was wondering if there's a way to access the previously stored entry in cache before updating it on swr situations, without doing another getItem in the storage.
I don't know if this is a good idea to add to the cache function handlers to make it work like a watcher, where we get the chance of getting the previous value and perform some validations on the update.
Is this something that is already available? Is this something that is planned for the future? Is this a bad idea am I having? 😂
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions