diff --git a/README.md b/README.md index 8903075..f0fc3cf 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,14 @@ cache.del(key) ```javascript await cache.del(`userInfo:${userId}`); ``` +### delAll +```javascript +cache.delAll(match, count) +``` + Return a Promise. +```javascript +await cache.delAll('userInfo:*', 100); +``` ### set: ```javascript cache.set(key, value) @@ -118,4 +126,8 @@ console.log(userInfo); // If the user is Updated, you can del or set the key to invalide the cache and requesting a new fetch on the next req. await cache.del(`userInfo:${userId}`); -``` \ No newline at end of file + +// If there are multiple users, you can delete all this keys +await cache.delAll('userInfo:*', 100); +``` + diff --git a/index.js b/index.js index f4dfd79..2c86211 100644 --- a/index.js +++ b/index.js @@ -104,6 +104,39 @@ class Cache { return true; }); } + + delAll(match, count = 100) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + reject(new Error('Timeout has occurred in delAll')) + }, 10000); + const promises = []; + const stream = this.cache.scanStream({ count, match }); + let pipeline = this.cache.pipeline(); + let nbWaiting = 0; + stream.on('data', (keys) => { + keys.forEach((key) => { + pipeline.del(key); + }); + nbWaiting += keys.length; + if (nbWaiting > count) { + promises.push(new Promise(resolve => pipeline.exec(resolve))); + nbWaiting = 0; + pipeline = this.cache.pipeline(); + } + }); + stream.on('end', async () => { + promises.push(new Promise(resolve => pipeline.exec(resolve))); + await Promise.all(promises); + clearTimeout(timeout); + resolve(); + }); + stream.on('error', (error) => { + clearTimeout(timeout); + reject(error); + }); + }); + } flush() { this.cache.flushall('ASYNC');