mirror of
https://github.com/aljazceru/ditto.git
synced 2026-01-15 11:24:26 +01:00
Rename all middleware to thingMiddleware
This commit is contained in:
28
src/middleware/cacheMiddleware.ts
Normal file
28
src/middleware/cacheMiddleware.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import Debug from '@soapbox/stickynotes/debug';
|
||||
import { type MiddlewareHandler } from 'hono';
|
||||
|
||||
import ExpiringCache from '@/utils/expiring-cache.ts';
|
||||
|
||||
const debug = Debug('ditto:middleware:cache');
|
||||
|
||||
export const cacheMiddleware = (options: {
|
||||
cacheName: string;
|
||||
expires?: number;
|
||||
}): MiddlewareHandler => {
|
||||
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) {
|
||||
debug('Building cache for page', c.req.url);
|
||||
await next();
|
||||
const response = c.res.clone();
|
||||
if (response.status < 500) {
|
||||
await cache.putExpiring(key, response, options.expires ?? 0);
|
||||
}
|
||||
} else {
|
||||
debug('Serving page from cache', c.req.url);
|
||||
return response;
|
||||
}
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user