-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
85 lines (69 loc) · 1.89 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
const debug = require('debug')('systemic:redis');
module.exports = (options) => {
let redis = (options && options.redis) || require('redis');
let client;
let config;
let logger;
const connectToRedis = async () => client.connect();
const start = async (dependencies) => {
debug(dependencies);
config = { ...dependencies.config };
if (!config) {
throw new Error('config is required');
}
({ logger } = dependencies);
if (!logger) {
logger = console;
}
// https://github.com/redis/node-redis#basic-example
const host = config.url || config.host || '127.0.0.1';
const database = config.db || 0;
let protocol = 'redis://';
const socket = {
connectTimeout: 10000,
keepAlive: 5000,
reconnectStrategy: retries => {
logger.info(`Reconnect attempt ${retries}`);
return 4000;
}
};
if (config.tls) {
protocol = 'rediss://';
socket.tls = true;
socket.servername = host;
}
const url = protocol + host + ':' + config.port + '/' + database;
client = redis.createClient({
url,
password: config.password,
socket,
});
client.on('connect', () => {
logger.info(`Try connecting ${url}`);
});
client.on('ready', () => {
logger.info(`Connected ${url}`);
});
// Without handling incoming server errors the process would get finished
client.on('error', error => {
if (error.message === 'ERR invalid password') {
throw error;
}
logger.error(`Client err: ${JSON.stringify(error)}`);
});
client.on('reconnecting', () => {
logger.info(`Redis client is reconnecting to ${url}...`)
});
if (config.no_ready_check) {
connectToRedis();
} else {
await connectToRedis();
}
return client;
};
const stop = async () => client.disconnect();
return {
start,
stop,
};
};