@azteam/redis-async
Version:
N/A
145 lines (118 loc) • 3.71 kB
JavaScript
import {createClient} from 'redis';
import {timeout} from '@azteam/util';
class RedisAsync {
constructor(config) {
this.connected = false;
this.host = config.host;
this.port = config.port;
this.prefix = config.prefix;
this.connect();
}
async waitConnection(n = 10) {
for (let i = 0; !this.connected || i < n; i += 1) {
await timeout(1000);
}
if (!this.connected) {
throw new Error('Redis not connected');
}
}
parsePrefix(name) {
if (this.prefix) {
return `${this.prefix}:${name}`;
}
return name;
}
connect() {
this._alert('connecting', 'Redis connecting...');
this.client = createClient({
host: this.host,
port: this.port,
retry_strategy: () => {
this.connected = false;
this._alert('connect', 'Redis disconnected');
this.client.quit();
},
});
this.client.connect();
this.client.on('connect', () => {
this.connected = true;
this._alert('connect', 'Redis connected');
});
this.client.on('end', () => {
this._alert('end', 'Redis end');
});
this.client.on('error', (err) => {
this._alert('error', `Redis Error${err}`);
});
}
async get(key, defaultValue = null) {
const prefixKey = this.parsePrefix(key);
if (this.connected) {
const data = await this.client.get(prefixKey);
if (data) {
return JSON.parse(data);
}
} else {
this.connect();
return null;
}
return defaultValue;
}
async ttl(key) {
const prefixKey = this.parsePrefix(key);
return this.client.ttl(prefixKey);
}
async expire(key, timeSecond = 86400) {
const prefixKey = this.parsePrefix(key);
this.client.expire(prefixKey, timeSecond);
}
async set(key, data, timeSecond = 86400, count = 0) {
const prefixKey = this.parsePrefix(key);
if (this.connected) {
await this.client.set(prefixKey, JSON.stringify(data));
await this.expire(prefixKey, timeSecond);
return true;
}
this.connect();
if (count < 5) {
return this.set(key, data, timeSecond, count + 1);
}
return false;
}
// async scan(pattern, cursor = 0, count = 1000) {
// const scanAsync = promisify(this.client.scan).bind(this.client);
// return await scanAsync(cursor, 'MATCH', pattern, 'COUNT', count);
// }
async remove(key, exact = true, count = 0) {
const prefixKey = this.parsePrefix(key);
if (this.connected) {
if (exact) {
await this.client.del(prefixKey);
} else {
const regexKey = `*${prefixKey}*`,
keys = await this.client.keys(regexKey);
if (keys.length > 0) {
return this.client.del(keys);
}
}
} else {
this.connect();
if (count < 5) {
return this.remove(key, exact, count + 1);
}
return false;
}
return false;
}
setAlertCallback(callback) {
this.alertCallback = callback;
}
_alert(status, msg) {
if (typeof this.alertCallback === 'function') {
this.alertCallback(status, msg);
} else {
console.error(status, msg);
}
}
}
export default RedisAsync;