Browse Source

refactor: extract _getAll method

master
Kiko Beats 3 years ago
parent
commit
c325d5a28d
No known key found for this signature in database GPG Key ID: 8FA93B22CCF04B96
  1. 49
      packages/keyv-redis/src/index.js

49
packages/keyv-redis/src/index.js

@ -22,6 +22,24 @@ class KeyvRedis extends EventEmitter {
this.redis.on('error', error => this.emit('error', error));
}
async _getAll({ onlyKeys = false } = {}) {
const stream = this.redis.scanStream({ match: `${this.namespace}*` });
const mget = this.redis.mget.bind(this.redis);
const data = [];
stream.on('data', async matchedKeys => {
if (onlyKeys) {
data.push(...matchedKeys);
} else {
const values = await mget(matchedKeys);
data.push(...matchedKeys.map((key, index) => ([key, values[index]])));
}
});
await pEvent(stream, 'end');
return data;
}
async get(key) {
const value = await this.redis.get(key);
return value === null ? undefined : value;
@ -48,36 +66,17 @@ class KeyvRedis extends EventEmitter {
return undefined;
}
const stream = this.redis.scanStream({ match: `${this.namespace}:*` });
const keys = [];
stream.on('data', matchedKeys => keys.push(...matchedKeys));
await pEvent(stream, 'end');
if (keys.length > 0) {
await this.redis.unlink(keys);
}
const keys = await this._getAll({ onlyKeys: true });
if (keys.length > 0) await this.redis.unlink(keys);
}
async * iterator() {
const scan = this.redis.scan.bind(this.redis);
const get = this.redis.mget.bind(this.redis);
async function * iterate(curs, pattern) {
const [cursor, keys] = await scan(curs, 'MATCH', pattern);
const values = await get(keys);
for (const i in keys) {
if (Object.prototype.hasOwnProperty.call(keys, i)) {
const key = keys[i];
const value = values[i];
yield [key, value];
}
}
if (cursor !== '0') {
yield * iterate(cursor, pattern);
const data = await this._getAll();
for (const item in data) {
if (Object.prototype.hasOwnProperty.call(data, item)) {
yield item;
}
}
yield * iterate(0, `${this.namespace}:*`);
}
}

Loading…
Cancel
Save