
Product
Introducing Reports: An Extensible Reporting Framework for Socket Data
Explore exportable charts for vulnerabilities, dependencies, and usage with Reports, Socket’s new extensible reporting framework.
ioredis-cache
Advanced tools
Compact redis cache using ioredis.
incr, hincrby,... npm install ioredis-cache
yarn add ioredis-cache
const Redis = require("ioredis")
const Cache = require("ioredis-cache")
const cache = new Cache(new Redis())
const value = await cache.cache("key", async () => ({ foo: "bar" }))
Depends on your case, you may want to disconnect redis after using:
cache.redis.quit()
#constructorconstructor(args: Redis | CacheOptions)
You can initialize the cache from an ioredis object or with options.
interface CacheOptions {
redis: object | Redis
parser: Parser
}
interface Parser { // Parse/unparse object when store in redis. Default is JSON
parse: (text: string) => any
stringify: (value: any) => string
}
#cachecache(key: string, callback: async (key: string) => any, ttl?: number): Promise<any>
Get the cached value of the key from redis. If the key does not exist, get the value from the callback, store it in redis and return the value.
If the callback return undefined, it will not be cached. null is cached normally.
If ttl is set, the key will expire after ttl second(s).
const getPost = (id) =>
cache(`post-${id}`, () => db.Post.getPostWithId(id), 60 * 60)
#getCachegetCache(key: string): Promise<any>
Get the cached value of the key from redis. If the key does not exist, return undefined.
#setCachesetCache(key: string, value: any, ttl?: number)
Store the value to the cache key.
If ttl is set, the key will expire after ttl second(s).
#manyCachemanyCache(keys: string[], callback: async (ids: string[]) => { [id: string]: any } | any[], prefix?: string, ttl?: number)
Get cached values for a list of keys from redis. The uncached keys will be passed to the callback to get the corresponding values. These values will be stored in redis. Returns combined array of both cached and uncached values.
If prefix is set, it will be preend to the key when get/set in redis. (The keys which are passed to the callback still don't have the prefix)
This is useful if some cached ids were invalidated, you can recache multiple values at once. For example:
// invalidate cache of the changed post
db.Post.onChange(post => cache.deleteCache(`post-${post.id}`))
// this function queries all posts that are uncached at once
const getPosts = (ids) =>
manyCache(ids, async (uncachedIds) => {
const posts = await db.Post.queryAllPostsWithIds(uncachedIds)
return posts.reduce((map, post) => Object.assign(map, { [post.id]: post }), {})
}, prefix: 'post-', 60 * 60)
#getManyCachegetManyCache(keys: string[]): Promise<any[]>
Return cached values for a list of keys from redis. If a key does not exist, the value will be undefined.
#setManyCachesetManyCache(keys: string[], ttl?: number)
Store the values with the corresponding keys in redis.
If ttl is set, the keys will expire after ttl second(s).
#deleteCachedeleteCache(...keys: string[]): Promise<number>
Delete the cached keys from redis and return the deleted number
#deletePatterndeletePattern(pattern: string, batch: number = 100)
Scan all keys and delete the keys that matched the pattern:
deletePattern('post:*')
Remove all cached keys start with "post:*".
#acquireacquire(key: string, amount: number, fn: (current: number) => any, float: boolean = false)
Increase the value of key by amount and pass it to fn function. If fn raises any exception, decrease the value of the key by amount.
By default, amount is treate as an integer. Set float = true if amount is a float.
#hashCachehashCache(key: string, id: string, callback: () => any): Promise<any>
Get the cached id of the key from redis. If the id or key does not exist, get the value from the callback, store it in redis and return the value.
This function is similar to #cache, but stores value in redis hash for better memory effeciency. You can remove the hash by simply deleting the cache key. This is better than using #deletePattern if there are a lot of keys to be deleted. The only downside is you can't set the ttl for each id but only for the hash.
#getHashCachegetHashCache(key: string, id: string): Promise<any>
Return the cached id of the key from redis. If the id / key does not exist, return undefined.
#setHashCachesetHashCache(key: string, value: any)
Store the value to the id of key
#hashManyCachehashManyCache(key: string, ids: string[], callback: (ids: string[]) => { [id: string]: any } | any[]): Promise<any[]>
Get cached values for the id array of the key from redis. The uncached ids will be passed to the callback to get the corresponding values. These values will be stored in redis. Returns a combined array of both cached and uncached values.
It is similar to #manyCache, but use redis hash to store data.
// invalidate cache of the changed post
db.Post.onChange(post => cache.deleteHashCache('post', post.id))
// this function queries all posts that are uncached at once
const getPosts = (ids) =>
hashManyCache('post', ids, async (uncachedIds) => {
const posts = await db.Post.queryAllPostsWithIds(uncachedIds)
return posts.reduce((map, post) => Object.assign(map, { [post.id]: post }), {})
})
#getHashManyCachegetHashManyCache(key: string, ids: string[]): Promise<any[]>
Return cached values for the id array of the key from redis. If the id / key does not exist, the value will be undefined.
#setHashManyCachesetHashManyCache(key: string, valueMap: { [id: string]: any })
Store the values with the corresponding ids of the key in redis
#deleteHashCachedeleteHashCache(key: string, ...ids: string[]): Promise<number>
Delete the cached ids of the key from redis and return the deleted number
#hashAcquirehashAcquire(key: string, id: string, amount: number, fn: (current: number) => any, float: boolean = false)
Increase the value of id in key by amount and pass it to fn function. If fn raises any exception, decrease the value of id in key by amount.
By default, amount is treated as an integer. Set float = true if amount is a float.
Make sure the redis is running at localhost:6379
Run the following command:
yarn test
FAQs
A promise-based cache package for Nodejs using IORedis
The npm package ioredis-cache receives a total of 6,272 weekly downloads. As such, ioredis-cache popularity was classified as popular.
We found that ioredis-cache demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Explore exportable charts for vulnerabilities, dependencies, and usage with Reports, Socket’s new extensible reporting framework.

Product
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.