-
Notifications
You must be signed in to change notification settings - Fork 186
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3715725
commit 7e06bd6
Showing
3 changed files
with
33 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,30 @@ | ||
import type { Redis } from 'ioredis' | ||
import { CacheProvider } from '@/modules/core/utils/cacheHandler' | ||
import { Logger } from 'pino' | ||
import { maybeLoggerWithContext } from '@/logging/requestContext' | ||
|
||
export const redisCacheFactory = <T>(deps: { | ||
redis: Redis | ||
options: { ttlMilliseconds: number } | ||
options: { ttlMilliseconds: number; logger?: Logger } | ||
}): CacheProvider<T> => { | ||
const { redis } = deps | ||
return { | ||
get: async (key: string) => { | ||
const result = await redis.get(key) | ||
return result ? (JSON.parse(result) as T) : undefined | ||
const reqLogger = maybeLoggerWithContext({ logger: deps.options.logger }) | ||
if (result) { | ||
reqLogger?.info(`Cache hit for key: '${key}'`) | ||
return JSON.parse(result) as T | ||
} | ||
|
||
reqLogger?.info(`Cache miss for key: '${key}'`) | ||
return undefined | ||
}, | ||
set: async (key: string, value: T) => { | ||
await redis.set( | ||
key, | ||
JSON.stringify(value), | ||
'EX', | ||
Math.floor(deps.options.ttlMilliseconds / 1000) // convert milliseconds to seconds | ||
) | ||
const reqLogger = maybeLoggerWithContext({ logger: deps.options.logger }) | ||
const ttl = Math.floor(deps.options.ttlMilliseconds / 1000) // convert milliseconds to seconds | ||
reqLogger?.info(`Upserting cache for key: '${key}' with ttl: ${ttl}s`) | ||
await redis.set(key, JSON.stringify(value), 'EX', ttl) | ||
} | ||
} | ||
} |