I was hoping to adjust the edge CacheTTL based on the contents of the Response. In my specific case, I wanted to pull a modified date on the page. If the modified date > XX days, I’d like to cache it longer.
Starting with this basic code:
self.addEventListener(‘fetch’, event => event.respondWith(handle(event)))
async function handle(event) {
const cache_time = 900
let cache = caches.default
let response = await cache.match(event.request)if (!response) {
response = await fetch(event.request, {
cf: {
cacheTtl: cache_time
}
});
event.waitUntil(cache.put(event.request, response.clone()))
}return response
};
The CacheTtl is set on the fetch event. So I tried to fetch again using a longer cache_time if my condition was met. But I couldn’t get it to work. It would never follow the new cache time. Here’s what I was trying to do:
self.addEventListener(‘fetch’, event => event.respondWith(handle(event)))
async function handle(event) {
const cache_time_long = 10000
const cache_time = 900
let cache = caches.default
let response = await cache.match(event.request)if (!response) {
response = await fetch(event.request, {
cf: {
cacheTtl: cache_time
}
});
let html = await response.text()if (some condition) { response = await fetch(event.request, { cf: { cacheTtl: cache_time_long } }); }
event.waitUntil(cache.put(event.request, response.clone()))
}return response
};
This didn’t work. Any suggestions if this is possible?