Created
October 23, 2020 06:18
-
-
Save vlio20/7131ea392080ab1acc1301b0edfe6cfe to your computer and use it in GitHub Desktop.
redis client wrapper for caching
This file contains hidden or 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
import {AsyncCache} from 'utils-decorators'; | |
import * as redis from 'redis'; | |
import {RedisClient} from 'redis'; | |
import {promisify} from 'util'; | |
import * as config from 'config'; | |
export class RedisCache<D> implements AsyncCache<D> { | |
delete: (key: string) => Promise<void>; | |
private readonly client: RedisClient; | |
private readonly clientSet: (key: string, value: string, unit: 'PX', ttl: number) => Promise<void>; | |
private readonly clientGet: (key: string) => Promise<string>; | |
private readonly cacheConf: CacheConf<D>; | |
constructor(cacheConf: CacheConf<D>) { | |
this.cacheConf = { | |
parse: JSON.parse, | |
stringify: JSON.stringify, | |
...cacheConf, | |
}; | |
const redisConf: RedisConf = config.get('redis'); | |
this.client = redis.createClient({ | |
host: redisConf.host, | |
port: redisConf.port, | |
...(redisConf.password && {password: redisConf.password}), | |
prefix: cacheConf.name, | |
}); | |
this.clientGet = promisify(this.client.get).bind(this.client); | |
this.clientSet = promisify(this.client.set).bind(this.client); | |
this.delete = promisify(this.client.del).bind(this.client); | |
} | |
async get(key: string): Promise<D> { | |
const strVal = await this.clientGet(key); | |
return strVal !== null ? this.cacheConf.parse(strVal) : null; | |
} | |
set(key: string, value: D): Promise<void> { | |
return this.clientSet(key, this.cacheConf.stringify(value), 'PX', this.cacheConf.ttl); | |
} | |
async has(key: string): Promise<boolean> { | |
return (await this.get(key)) !== null; | |
} | |
} | |
interface RedisConf { | |
host: string; | |
port: number; | |
password: string; | |
} | |
interface CacheConf<D> { | |
name: string; | |
ttl: number; | |
parse?: (val: string) => D; | |
stringify?: (val: D) => string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment