Skip to content

Commit

Permalink
fix: 🐛 ttl in response in seconds (#611)
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelromon authored Nov 1, 2024
1 parent 22250d8 commit df6468d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/quick-ways-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sebspark/promise-cache": patch
---

ttl in response should be in seconds
2 changes: 1 addition & 1 deletion packages/promise-cache/src/promiseCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ describe('PromiseCache', () => {
// Cache should be set with the TTL from the response
expect(mockedPersistorSet).toHaveBeenCalledWith('testkey4', {
timestamp: expect.any(Number),
ttl: 112312,
ttl: 112312000,
value: {
value: 42,
ttl: '112312',
Expand Down
11 changes: 6 additions & 5 deletions packages/promise-cache/src/promiseCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,14 @@ export class PromiseCache<U> {
* @param key Cache key.
* @param delegate The function to execute if the key is not in the cache.
* @param ttlInSeconds Time to live in seconds.
* @param ttlKey The key in the response object that contains the TTL.
* @param ttlKeyInSeconds The key in the response object that contains the TTL.
* @returns The result of the delegate function.
*/
async wrap(
key: string,
delegate: () => Promise<U>,
ttlInSeconds?: number,
ttlKey?: string
ttlKeyInSeconds?: string
): Promise<U> {
const now = Date.now()

Expand All @@ -141,7 +141,7 @@ export class PromiseCache<U> {
const cached = await this.persistor.get<U>(effectiveKey)

if (cached) {
if (!ttlKey && cached.ttl !== effectiveTTL) {
if (!ttlKeyInSeconds && cached.ttl !== effectiveTTL) {
console.error(
`WARNING: TTL mismatch for key: ${effectiveKey}. It is recommended to use the same TTL for the same key.`
)
Expand All @@ -154,9 +154,10 @@ export class PromiseCache<U> {
const response = await delegate()

// Get the TTL from the response if a TTL key is provided.
if (ttlKey) {
if (ttlKeyInSeconds) {
const responseDict = response as Record<string, unknown>
effectiveTTL = Number(responseDict[ttlKey] as string) || effectiveTTL // Fall back to the default TTL if the TTL key is not found.
const responseTTL = Number(responseDict[ttlKeyInSeconds] as string) * 1000
effectiveTTL = responseTTL || effectiveTTL // Fall back to the default TTL if the TTL key is not found.
}

this.persistor.set(effectiveKey, {
Expand Down

0 comments on commit df6468d

Please sign in to comment.