feat: add cache response header if caching is enabled

This commit is contained in:
Ritesh Ghosh
2025-05-25 22:46:06 +05:30
parent 74c9ffcb8f
commit 013196bd3d
+39 -6
View File
@@ -1,6 +1,8 @@
import type { MiddlewareHandler } from "hono";
import { env } from "../config/env.js"; import { env } from "../config/env.js";
import { AniwatchAPICache } from "../config/cache.js"; import { AniwatchAPICache, cache } from "../config/cache.js";
import type { BlankInput } from "hono/types";
import type { Context, MiddlewareHandler } from "hono";
import type { ServerContext } from "../config/variables.js";
// Define middleware to add Cache-Control header // Define middleware to add Cache-Control header
export const cacheControl: MiddlewareHandler = async (c, next) => { export const cacheControl: MiddlewareHandler = async (c, next) => {
@@ -19,14 +21,45 @@ export function cacheConfigSetter(keySliceIndex: number): MiddlewareHandler {
return async (c, next) => { return async (c, next) => {
const { pathname, search } = new URL(c.req.url); const { pathname, search } = new URL(c.req.url);
const duration = Number(
c.req.header(AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME) ||
AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS
);
c.set("CACHE_CONFIG", { c.set("CACHE_CONFIG", {
key: `${pathname.slice(keySliceIndex) + search}`, key: `${pathname.slice(keySliceIndex) + search}`,
duration: Number( duration,
c.req.header(AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME) ||
AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS
),
}); });
if (AniwatchAPICache.enabled) {
c.res.headers.set(
AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME,
duration.toString()
);
}
await next(); await next();
}; };
} }
export function withCache<T, P extends string = string>(
getData: (c: Context<ServerContext, P, BlankInput>) => Promise<T>
) {
return async (c: Context<ServerContext, P, BlankInput>) => {
const cacheConfig = c.get("CACHE_CONFIG");
const data = await cache.getOrSet<T>(
() => getData(c),
cacheConfig.key,
cacheConfig.duration
);
return c.json({ status: 200, data }, { status: 200 });
};
}
// export function _withCache<T>(
// context: Context<ServerContext>,
// promise: Promise<T>
// ): MiddlewareHandler {
// return async (c) => {};
// }