This repository was archived by the owner on Sep 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
173 lines (152 loc) · 5.72 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
const EventEmitter = require('events');
const _ = require('lodash');
module.exports = class RedisConfigManager extends EventEmitter {
constructor(params) {
super();
params = _.clone(params); // avoid mucking up the original params;
if (!params.hashKey) {
throw new Error('param.hashKey string required');
}
// general configuration
const paramDefaults = {
label: `NO-LABEL RedisConfigManager Instance`,
hashKeyPrefix: 'redis-config-manager:',
hashKey: undefined,
refreshInterval: 1000 * 15,
fixtureData: undefined,
listeners: {
debug: console.log,
ready: console.log,
error: console.error,
},
};
const redisDefaults = {
host: '127.0.0.1',
port: 6379,
db: 0,
module_override: undefined,
client_override: undefined,
};
this.redisParams = Object.assign({}, redisDefaults, params.client);
delete params.client;
// params = _.omit(params, ['client']);
this.options = Object.assign({}, paramDefaults, params);
// local state
this.hashKey = `${this.options.hashKeyPrefix}${this.options.hashKey}`;
this.activeConfigKeys = new Set([]);
this.activeConfigKeysLastUpdate = null;
this.initKeyInterval;
}
async init() {
this.initEventListeners();
await this.initRedisClient();
this.initAsyncCommands();
await this.loadFixtureData();
await this.initKeyRefresh();
this.emit('debug', '---> init completed');
}
stop() {
clearInterval(this.initKeyInterval);
this.emit('debug', '... stop completed');
}
initEventListeners() {
if (!this.options.listeners) {
return;
}
for (const key of Object.keys(this.options.listeners)) {
this.on(key, this.options.listeners[key]);
}
}
isConnected() {
return this.redisClient && this.redisClient.connected;
}
initRedisClient() {
const self = this;
const redisModule = this.redisParams.module_override || require('redis');
this.redisClient = this.redisParams.client_override || redisModule.createClient(this.redisParams);
return new Promise((resolve, reject) => {
this.redisClient
.on('error', (error) => {
const msg = `Redis error => ${self.options.label} : ${error.message}`;
self.emit('error', msg);
})
.on('ready', () => {
if (this.options.db) {
self.redisClient.select(self.redisParams.db);
}
let msg = `Redis connected => ${self.options.label} to redis://${
self.redisClient.address || 'mock_redis_instance'
}`;
if (this.options.db > 0) {
msg += `/db${self.redisParams.db}`;
}
if (self.redisClient.server_info && self.redisClient.server_info.redis_version) {
msg += ` v${self.redisClient.server_info.redis_version}`;
}
self.emit('ready', msg);
resolve();
});
if (this.isConnected()) {
// handles pre-existing clients that may already be connected;
resolve();
}
});
}
initAsyncCommands() {
const self = this;
const { promisify } = require('util');
const commands = ['ping', 'hget', 'hset', 'hdel', 'hmget', 'hkeys', 'hexists'];
this.cmd = commands.reduce(
(o, key) => ({ ...o, [key]: promisify(self.redisClient[key]).bind(self.redisClient) }),
{}
);
}
async initKeyRefresh() {
const self = this;
await self.keyRefresh();
self.initKeyInterval = setInterval(self.keyRefresh.bind(self), self.options.refreshInterval);
}
async keyRefresh() {
const allKeys = await this.cmd.hkeys(this.hashKey);
this.activeConfigKeys = new Set(allKeys);
}
hasConfigKey(key) {
return this.activeConfigKeys.has(key);
}
async getConfig(key) {
const result = await this.cmd.hget(this.hashKey, key);
this.emit('debug', `getConfig: ${this.hashKey}, ${key}, ${result}`);
return result ? JSON.parse(result) : result;
}
async getConfigs(keys) {
this.emit('debug', `getConfigs: ${keys}`);
if (!Array.isArray(keys)) {
throw new Error(`getConfigs requires an array of keys be passed in`);
}
const results = await this.cmd.hmget(this.hashKey, keys);
this.emit('debug', `getConfigs ${this.hashKey}, ${keys}`);
return results.map((r) => (r ? JSON.parse(r) : r));
}
async setConfig(key, value) {
value.last_updated = new Date().getTime();
const serialized = JSON.stringify(value);
await this.cmd.hset(this.hashKey, key, serialized);
this.emit('debug', `setConfig ${this.hashKey}, ${key}, ${serialized}`);
return true;
}
async delConfig(key) {
await this.cmd.hdel(this.hashKey, key);
return true;
}
async loadFixtureData() {
const self = this;
if (!this.options.fixtureData) {
return;
}
for (const key of Object.keys(this.options.fixtureData)) {
const config = this.options.fixtureData[key];
await self.setConfig(key, config);
self.emit('debug', `Fixture Data loaded for ${self.options.label}: ${key}`);
}
}
};