From 013196bd3d5e44aa76b1825f24f9f5186fe7e7c1 Mon Sep 17 00:00:00 2001 From: Ritesh Ghosh Date: Sun, 25 May 2025 22:46:06 +0530 Subject: [PATCH] feat: add cache response header if caching is enabled --- src/middleware/cache.ts | 45 +++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/src/middleware/cache.ts b/src/middleware/cache.ts index 164f4a3..8fd3dc8 100644 --- a/src/middleware/cache.ts +++ b/src/middleware/cache.ts @@ -1,6 +1,8 @@ -import type { MiddlewareHandler } from "hono"; 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 export const cacheControl: MiddlewareHandler = async (c, next) => { @@ -19,14 +21,45 @@ export function cacheConfigSetter(keySliceIndex: number): MiddlewareHandler { return async (c, next) => { 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", { key: `${pathname.slice(keySliceIndex) + search}`, - duration: Number( - c.req.header(AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME) || - AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS - ), + duration, }); + if (AniwatchAPICache.enabled) { + c.res.headers.set( + AniwatchAPICache.CACHE_EXPIRY_HEADER_NAME, + duration.toString() + ); + } + await next(); }; } + +export function withCache( + getData: (c: Context) => Promise +) { + return async (c: Context) => { + const cacheConfig = c.get("CACHE_CONFIG"); + + const data = await cache.getOrSet( + () => getData(c), + cacheConfig.key, + cacheConfig.duration + ); + + return c.json({ status: 200, data }, { status: 200 }); + }; +} + +// export function _withCache( +// context: Context, +// promise: Promise +// ): MiddlewareHandler { +// return async (c) => {}; +// }