Skip to content

Commit

Permalink
feat(cache): add cacheConfigSetter & cacheControlMiddleware by #90
Browse files Browse the repository at this point in the history
  • Loading branch information
ghoshRitesh12 committed Dec 24, 2024
1 parent d939222 commit 5f1f216
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
15 changes: 0 additions & 15 deletions src/config/cacheControlMiddleware.ts

This file was deleted.

35 changes: 35 additions & 0 deletions src/middleware/cache.ts
Original file line number Diff line number Diff line change
@@ -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();
};
}

0 comments on commit 5f1f216

Please sign in to comment.