mirror of
https://github.com/aljazceru/ditto.git
synced 2025-12-29 19:24:25 +01:00
cache: serve stale response
This commit is contained in:
@@ -12,19 +12,32 @@ export const cache = (opts: CacheOpts): MiddlewareHandler => {
|
||||
let expires = Date.now() + opts.expires;
|
||||
|
||||
return async (c, next) => {
|
||||
if (!response || (Date.now() > expires)) {
|
||||
debug('Building cache for page', c.req.url);
|
||||
expires = Date.now() + opts.expires;
|
||||
const now = Date.now();
|
||||
const expired = now > expires;
|
||||
|
||||
async function updateCache() {
|
||||
await next();
|
||||
|
||||
const res = c.res.clone();
|
||||
if (res.status < 500) {
|
||||
response = res;
|
||||
}
|
||||
} else {
|
||||
return res;
|
||||
}
|
||||
|
||||
if (response && !expired) {
|
||||
debug('Serving page from cache', c.req.url);
|
||||
return response.clone();
|
||||
} else {
|
||||
expires = Date.now() + opts.expires;
|
||||
if (response && expired) {
|
||||
debug('Serving stale cache, rebuilding', c.req.url);
|
||||
const stale = response.clone();
|
||||
updateCache();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
return stale;
|
||||
}
|
||||
debug('Building cache for page', c.req.url);
|
||||
return await updateCache();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user