feat(cache): add Cache-Control middleware and update .env.example

This commit is contained in:
Abdelaziz Mahdy
2024-12-22 15:32:56 -04:00
parent 2d5377cbc5
commit f1f5db84f9
3 changed files with 23 additions and 0 deletions
+6
View File
@@ -23,3 +23,9 @@ ANIWATCH_API_MAX_REQS=70
# env to use optional redis caching functionality
ANIWATCH_API_REDIS_CONN_URL=<rediss://default:your-secure-password@your-redis-instance-name.provider.com:6379>
# Cache-Control settings for Vercel Edge Caching
# s-maxage specifies the maximum amount of time a resource is considered fresh when served by a CDN cache
S_MAXAGE=60
# stale-while-revalidate specifies the amount of time a resource is served stale while a new one is fetched
STALE_WHILE_REVALIDATE=30
+15
View File
@@ -0,0 +1,15 @@
import type { MiddlewareHandler } from "hono";
// Define middleware to add Cache-Control header
const cacheControlMiddleware: MiddlewareHandler = async (c, next) => {
const sMaxAge = process.env.S_MAXAGE || "60";
const staleWhileRevalidate = process.env.STALE_WHILE_REVALIDATE || "30";
c.header(
"Cache-Control",
`s-maxage=${sMaxAge}, stale-while-revalidate=${staleWhileRevalidate}`
);
await next();
};
export default cacheControlMiddleware;
+2
View File
@@ -5,6 +5,7 @@ import corsConfig from "./config/cors.js";
import { ratelimit } from "./config/ratelimit.js";
import { hianimeRouter } from "./routes/hianime.js";
import cacheControlMiddleware from "./config/cache_control_middleware.js";
import { Hono } from "hono";
import { logger } from "hono/logger";
@@ -26,6 +27,7 @@ const app = new Hono<{ Variables: AniwatchAPIVariables }>();
app.use(logger());
app.use(corsConfig);
app.use(cacheControlMiddleware);
// CAUTION: For personal deployments, "refrain" from having an env
// named "ANIWATCH_API_HOSTNAME". You may face rate limitting