Rework cache middleware to use in-memory cache, remove ExpiringCache module

This commit is contained in:
Alex Gleason
2024-04-13 14:00:21 -05:00
parent a738ed3d4d
commit 6ab3a640bf
4 changed files with 21 additions and 103 deletions

View File

@@ -1,26 +1,30 @@
import { Debug, type MiddlewareHandler } from '@/deps.ts';
import ExpiringCache from '@/utils/expiring-cache.ts';
const debug = Debug('ditto:middleware:cache');
export const cache = (options: {
cacheName: string;
expires?: number;
}): MiddlewareHandler => {
interface CacheOpts {
expires: number;
}
/** In-memory cache middleware. */
export const cache = (opts: CacheOpts): MiddlewareHandler => {
let response: Response | undefined;
let expires = Date.now() + opts.expires;
return async (c, next) => {
const key = c.req.url.replace('http://', 'https://');
const cache = new ExpiringCache(await caches.open(options.cacheName));
const response = await cache.match(key);
if (!response) {
if (!response || (Date.now() > expires)) {
debug('Building cache for page', c.req.url);
expires = Date.now() + opts.expires;
await next();
const response = c.res.clone();
if (response.status < 500) {
await cache.putExpiring(key, response, options.expires ?? 0);
const res = c.res.clone();
if (res.status < 500) {
response = res;
}
} else {
debug('Serving page from cache', c.req.url);
return response;
return response.clone();
}
};
};