UNPKG

2.33 kBJavaScriptView Raw
1'use strict';
2
3const redis = require('redis');
4const helpers = require('./helpers');
5
6function createClient(settings, createNew) {
7 let client;
8 if (isClient(settings)) {
9 // We assume it's a redis client from either node_redis or ioredis.
10 client = settings;
11
12 if (createNew) {
13 // Both node_redis and ioredis support the duplicate method, which creates
14 // a new redis client with the same configuration.
15 client = client.duplicate();
16 } else if (isReady(client)) {
17 // If we were given a redis client, and we don't want to clone it (to
18 // enable connection sharing between Queue instances), and it's already
19 // ready, then just return it.
20 return Promise.resolve(client);
21 } // otherwise, we wait for the client to be in the ready state.
22 } else {
23 // node_redis mutates the options object we provide it, so we clone the
24 // settings first.
25 if (typeof settings === 'object') {
26 settings = Object.assign({}, settings);
27 }
28
29 client = redis.createClient(settings);
30 }
31
32 // Wait for the client to be ready, then resolve with the client itself.
33 return helpers.waitOn(client, 'ready', true)
34 .then(() => client);
35}
36
37function disconnect(client) {
38 // Redis#end is deprecated for ioredis.
39 /* istanbul ignore if: this is only for ioredis */
40 if (client.disconnect) {
41 client.disconnect();
42 } else {
43 // true indicates that it should invoke all pending callbacks with an
44 // AbortError; we need this behavior.
45 client.end(true);
46 }
47}
48
49function isAbortError(err) {
50 // node_redis has a designated class for abort errors, but ioredis just has
51 // a constant message defined in a utils file.
52 return err.name === 'AbortError' ||
53 /* istanbul ignore next: this is only for ioredis */
54 err.message === 'Connection is closed.';
55}
56
57function isClient(object) {
58 if (!object || typeof object !== 'object') return false;
59 const name = object.constructor.name;
60 return name === 'Redis' || name === 'RedisClient';
61}
62
63function isReady(client) {
64 // node_redis has a ready property, ioredis has a status property.
65 return client.ready || client.status === 'ready';
66}
67
68exports.createClient = createClient;
69exports.disconnect = disconnect;
70exports.isAbortError = isAbortError;
71exports.isClient = isClient;
72exports.isReady = isReady;