mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-03 21:54:23 +01:00
Rework cache middleware to use in-memory cache, remove ExpiringCache module
This commit is contained in:
@@ -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();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user