Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add the method of deleting keys by regular express #1

Merged
merged 1 commit into from Dec 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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'
);
});