ofetch
ofetch copied to clipboard
feat: support a way to override fetching behavior
What's the best way to cache responses with ohmyfetch via an LRU cache?
With axios, I've used axios-extensions's "cacheAdapterEnhancer" like so:
import { cacheAdapterEnhancer } from 'axios-extensions';
import LRU from 'lru-cache';
const ONE_HOUR = 1000 * 60 * 60;
const defaultCache = new LRU({ maxAge: ONE_HOUR });
const defaults = $axios.defaults;
defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
enabledByDefault: false,
cacheFlag: 'useCache',
defaultCache,
});
which caches responses when I explicitly add useCache: true to the request.
Is there a similar enhancer for ohmyfetch, or one planned, or an example of how to implement caching with ohmyfetch?
Maybe something similar to this? https://mihanizm56.github.io/fetch-api/docs/examples/caching
As far as I see the code, currently there doesn't seem to be a point at which we can override fetching behavior (type of onRequest hook is void so it has no influence on the behavior).
I will add a label to this issue for now.
This was approximately the solution I came up with since I originally posted this issue:
// Create a new LRU cache with a maximum size of
// 100 items and a time-to-live of one hour
import LRU from 'lru-cache';
const cache = new LRU({
max: 100,
ttl: 1000 * 60 * 60, // One hour
});
async function attemptFetch() {
try {
const response = await fetchData(event.node.req.url,
method,
params,
body,
headers,
authorization,
);
// Set the response in the cache
cache.set(event.node.req.url, response);
return response;
}
catch (error) {
// Attempt to fetch the data
return attemptFetch();
}
}
// Check if the URL is already in the cache
if (!cache.get(event.node.req.url) {
return attemptFetch();
} else {
// If the URL is already in the cache, just return the cached response
return await cache.get(event.node.req.url);
}
fetchData is just a wrapper for ofetch.