1 | import redis from 'redis';
|
2 | import clui from 'clui';
|
3 |
|
4 | let countdown = new clui.Spinner();
|
5 | let started;
|
6 |
|
7 | export const createClient = (config, { debug } = { debug: false }) => {
|
8 | const client = redis.createClient({
|
9 | ...config,
|
10 | retry_strategy: ({ attempt, total_retry_time, error, time_connected }) => {
|
11 | if (attempt > 20) {
|
12 | return;
|
13 | }
|
14 |
|
15 | return Math.min(attempt * 100, 3000);
|
16 | },
|
17 | });
|
18 |
|
19 | client.on('connect', () => {
|
20 | if (debug) {
|
21 | started = false;
|
22 | countdown.stop();
|
23 | console.log('connected');
|
24 | }
|
25 | });
|
26 |
|
27 | client.on('reconnecting', ({ delay, attempt }) => {
|
28 | if (debug) {
|
29 | countdown.message(
|
30 | `attempting (${attempt}) to reconnect in ${delay}ms...`
|
31 | );
|
32 | if (!started) {
|
33 | started = true;
|
34 | countdown.start();
|
35 | }
|
36 | }
|
37 | });
|
38 |
|
39 | process.on('exit', () => {
|
40 | debug && console.log('client is quiting forcefully');
|
41 | client.end(true);
|
42 | });
|
43 |
|
44 | return client;
|
45 | };
|
46 |
|
47 | const defaultClient = createClient({
|
48 | url: process.env.REDIS_URL,
|
49 | });
|
50 |
|
51 | export default defaultClient;
|
52 |
|
53 | export type RedisClientType = typeof defaultClient;
|