From 0602fdd6518a350252a16a68f2104b3059d9bebf Mon Sep 17 00:00:00 2001 From: Ajay Date: Thu, 11 Apr 2024 17:54:32 -0400 Subject: [PATCH] Use cache for ttl if possible Also fixes etag when compression enabled --- src/middleware/etag.ts | 2 +- src/utils/queryCacher.ts | 1 + src/utils/redis.ts | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/middleware/etag.ts b/src/middleware/etag.ts index 0e94d97..786586f 100644 --- a/src/middleware/etag.ts +++ b/src/middleware/etag.ts @@ -38,7 +38,7 @@ function getLastModified(hashType: hashType, hashKey: hashKey, service: Service) export async function getEtag(hashType: hashType, hashKey: hashKey, service: Service): Promise { const lastModified = await getLastModified(hashType, hashKey, service); - return `${hashType};${hashKey};${service};${lastModified.getTime()}` as ETag; + return `"${hashType};${hashKey};${service};${lastModified.getTime()}"` as ETag; } /* example usage diff --git a/src/utils/queryCacher.ts b/src/utils/queryCacher.ts index 317bb58..69dff0d 100644 --- a/src/utils/queryCacher.ts +++ b/src/utils/queryCacher.ts @@ -143,6 +143,7 @@ async function getKeyLastModified(key: string): Promise { if (!config.redis?.enabled) return Promise.reject("ETag - Redis not enabled"); return await redis.ttl(key) .then(ttl => { + if (ttl <= 0) return new Date(); const sinceLive = config.redis?.expiryTime - ttl; const now = Math.floor(Date.now() / 1000); return new Date((now-sinceLive) * 1000); diff --git a/src/utils/redis.ts b/src/utils/redis.ts index 1d33e81..a5cd89d 100644 --- a/src/utils/redis.ts +++ b/src/utils/redis.ts @@ -193,6 +193,15 @@ if (config.redis?.enabled) { } }; + const ttl = client.ttl.bind(client); + exportClient.ttl = (key) => { + if (cache && cacheClient && cache.has(key)) { + return Promise.resolve(config.redis?.expiryTime - Math.floor((cache.ttl - cache.info(key).ttl) / 1000)); + } else { + return ttl(createKeyName(key)); + } + }; + const get = client.get.bind(client); const getRead = readClient?.get?.bind(readClient); exportClient.get = (key) => new Promise((resolve, reject) => {