Skip to content

Commit

Permalink
Add prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
kibertoad committed Oct 7, 2022
1 parent 4249108 commit 4f8ba8a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
14 changes: 10 additions & 4 deletions lib/redis/RedisCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { Cache, CacheConfiguration, Loader } from '../DataSources'
import type { Redis } from 'ioredis'

export interface RedisCacheConfiguration extends CacheConfiguration {
prefix: string
json: boolean
}

const DefaultConfiguration: RedisCacheConfiguration = {
json: false,
prefix: 'layered-cache:',
ttlInMsecs: 1000 * 60 * 10,
}

Expand All @@ -26,11 +28,11 @@ export class RedisCache<T> implements Cache<T>, Loader<T> {
}

async delete(key: string): Promise<void> {
await this.redis.del(key)
await this.redis.del(this.resolveKey(key))
}

async get(key: string): Promise<T | undefined> {
const redisResult = await this.redis.get(key)
const redisResult = await this.redis.get(this.resolveKey(key))
if (redisResult && this.config.json) {
return JSON.parse(redisResult)
}
Expand All @@ -48,9 +50,13 @@ export class RedisCache<T> implements Cache<T>, Loader<T> {
const resolvedValue: string = value && this.config.json ? JSON.stringify(value) : (value as unknown as string)

if (this.config.ttlInMsecs) {
await this.redis.set(key, resolvedValue, 'PX', this.config.ttlInMsecs)
await this.redis.set(this.resolveKey(key), resolvedValue, 'PX', this.config.ttlInMsecs)
return
}
await this.redis.set(key, resolvedValue)
await this.redis.set(this.resolveKey(key), resolvedValue)
}

resolveKey(key: string) {
return `${this.config.prefix}${key}`
}
}
9 changes: 6 additions & 3 deletions test/RedisCache.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import Redis from 'ioredis'
import Redis, { RedisOptions } from 'ioredis'
import { RedisCache } from '../lib/redis/RedisCache'

const redisOptions: Redis.RedisOptions = {
const redisOptions: RedisOptions = {
host: 'localhost',
port: 6379,
password: 'sOmE_sEcUrE_pAsS',
}

describe('RedisCache', () => {
let redis: Redis.Redis
let redis: Redis
beforeEach(async () => {
redis = new Redis(redisOptions)
})
Expand Down Expand Up @@ -52,6 +52,8 @@ describe('RedisCache', () => {
it('sets json values correctly', async () => {
const cache = new RedisCache(redis, {
json: true,
prefix: 'cache',
ttlInMsecs: 5000,
})
await cache.set('key', { value: 'value' })
await cache.set('key2', { value: 'value2' })
Expand All @@ -67,6 +69,7 @@ describe('RedisCache', () => {
const cache = new RedisCache(redis, {
json: true,
ttlInMsecs: 10000,
prefix: 'cache:',
})
await cache.set('key', { value: 'value' })
await cache.set('key2', { value: 'value2' })
Expand Down

0 comments on commit 4f8ba8a

Please sign in to comment.