Skip to content

Commit

Permalink
Merge pull request #1 from kyohaifeng/think-redis-delKeys
Browse files Browse the repository at this point in the history
add the method of deleting keys by regular express
  • Loading branch information
lizheming committed Dec 3, 2019
2 parents de6bcc5 + 272d244 commit 6a559ec
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
33 changes: 33 additions & 0 deletions index.js
Expand Up @@ -101,6 +101,39 @@ class thinkRedis {
return this.redis.del(key);
}

/**
* delete Regular expressions key
* @param regKey
* @return {Promise} [description]
*/
deleteRegKey(regKey) {
return new Promise((resolve, reject) => {
const stream = this.redis.scanStream({
match: regKey
});
stream.on('data', (keys = []) => {
stream.pause();
if (keys.length) {
var pipeline = this.redis.pipeline();
keys.forEach(function(key) {
pipeline.del(key);
});
pipeline.exec().then((res) => {
stream.resume();
}).catch((err) => {
err.pattern = regKey;
reject(err);
});
} else {
resolve('NO_KEYS');
}
});
stream.on('end', () => {
resolve('OK');
});
});
}

/**
* increase key's value
* @param {String} key [description]
Expand Down
11 changes: 11 additions & 0 deletions test/index.js
Expand Up @@ -55,3 +55,14 @@ test.serial('set key and then incr & decr ', async t => {
t.true(g1 === '101' && g2 === '100');
});

test.serial('clear keys', async t => {
const keys = 'na*';
const redisInst = new Redis();
const s = await redisInst.set('name2', 'lushijie');
const g1 = await redisInst.get('name2');
const result = await redisInst.deleteRegKey(keys);
const g2 = await redisInst.get('name2');
t.true(
g1 === 'lushijie' && g2 === null && result === 'OK'
);
});

0 comments on commit 6a559ec

Please sign in to comment.