Skip to content

Commit

Permalink
feat: add delAll method (#2)
Browse files Browse the repository at this point in the history
* feat: add delAll method

* fix: add delAll documentation, upgrade wording

* fix: correct delAll documentation

Co-authored-by: Dali Dosso-Dautais <dali@hicsuntdev.com>
  • Loading branch information
dalidossodautais and HSD-Dali committed May 15, 2020
1 parent 967911f commit 1d36aa2
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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}`);
```

// If there are multiple users, you can delete all this keys
await cache.delAll('userInfo:*', 100);
```

33 changes: 33 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 1d36aa2

Please sign in to comment.