1.1.0 • Published 8 months ago
skutil-redis v1.1.0
ioredis wrapper for skutil Merges two clients(regular mode and subscribe mode) together
Install
yarn add skutil-redis
Usage
const RedisClient = require('skutil-redis')
const client = new RedisClient({
host: '127.0.0.1',
port: 6379,
keyPrefix: 'skutil:'
}, {
logger: console
})
interfaces from ioredis
The RedisClient extends from ioredis client.
functions in this lib
////////////////////////////////
// setObj/getObj
client.setObj(key, {a: 1, b: 2})
const obj = await client.getObj(key)
// obj = {a: 1, b: 2}
////////////////////////////////
// pub/sub
client.subCh(channel, (message) => {
// ...
})
client.unsubCh(channel)
client.publish(channel, message)
////////////////////////////////
// convenient cache
async function func1(a, b) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(a+b)
}, 100)
})
}
const cachedFunc = client.redisify(func1, key, expire)
// first call: cache not exist, call the original func1
const result = await cachedFunc(2, 3)
assert(result === 5)
// before expire: return the cached value
const result2 = await cachedFunc(2, 8)
assert(result === 5)
// after expire: call the original func1, then set the new cache
const result2 = await cachedFunc(2, 8)
assert(result === 10)
// force invalidate the cached result
client.invalidateAutoCache(key)