diff --git a/src/config/cacheControlMiddleware.ts b/src/config/cacheControlMiddleware.ts deleted file mode 100644 index 47035ed..0000000 --- a/src/config/cacheControlMiddleware.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { MiddlewareHandler } from "hono"; - -// Define middleware to add Cache-Control header -const cacheControlMiddleware: MiddlewareHandler = async (c, next) => { - const sMaxAge = process.env.ANIWATCH_API_S_MAXAGE || "60"; - const staleWhileRevalidate = process.env.ANIWATCH_API_STALE_WHILE_REVALIDATE || "30"; - c.header( - "Cache-Control", - `s-maxage=${sMaxAge}, stale-while-revalidate=${staleWhileRevalidate}` - ); - - await next(); -}; - -export default cacheControlMiddleware; diff --git a/src/middleware/cache.ts b/src/middleware/cache.ts new file mode 100644 index 0000000..fc249c2 --- /dev/null +++ b/src/middleware/cache.ts @@ -0,0 +1,35 @@ +import { config } from "dotenv"; +import { AniwatchAPICache } from "../config/cache.js"; +import type { MiddlewareHandler } from "hono"; + +config(); + +// Define middleware to add Cache-Control header +export const cacheControlMiddleware: MiddlewareHandler = async (c, next) => { + const sMaxAge = process.env.ANIWATCH_API_S_MAXAGE || "60"; + const staleWhileRevalidate = + process.env.ANIWATCH_API_STALE_WHILE_REVALIDATE || "30"; + + c.header( + "Cache-Control", + `s-maxage=${sMaxAge}, stale-while-revalidate=${staleWhileRevalidate}` + ); + + await next(); +}; + +export function cacheConfigSetter(keySliceIndex: number): MiddlewareHandler { + return async (c, next) => { + const { pathname, search } = new URL(c.req.url); + + c.set("CACHE_CONFIG", { + key: `${pathname.slice(keySliceIndex) + search}`, + duration: Number( + c.req.header(AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME) || + AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS + ), + }); + + await next(); + }; +}