UNPKG

3.34 kBJavaScriptView Raw
1'use strict';
2
3var utils = require('./utils');
4var URL = require('url');
5
6module.exports = function createClient (port_arg, host_arg, options) {
7
8 if (typeof port_arg === 'number' || typeof port_arg === 'string' && /^\d+$/.test(port_arg)) {
9
10 var host;
11 if (typeof host_arg === 'string') {
12 host = host_arg;
13 } else {
14 if (options && host_arg) {
15 throw new TypeError('Unknown type of connection in createClient()');
16 }
17 options = options || host_arg;
18 }
19 options = utils.clone(options);
20 options.host = host || options.host;
21 options.port = port_arg;
22
23 } else if (typeof port_arg === 'string' || port_arg && port_arg.url) {
24
25 options = utils.clone(port_arg.url ? port_arg : host_arg || options);
26 var url = port_arg.url || port_arg;
27 var parsed = URL.parse(url, true, true);
28
29 // [redis:]//[[user][:password]@][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]]
30 if (parsed.slashes) { // We require slashes
31 if (parsed.auth) {
32 options.password = parsed.auth.slice(parsed.auth.indexOf(':') + 1);
33 }
34 if (parsed.protocol) {
35 if (parsed.protocol === 'rediss:') {
36 options.tls = options.tls || {};
37 } else if (parsed.protocol !== 'redis:') {
38 console.warn('node_redis: WARNING: You passed "' + parsed.protocol.substring(0, parsed.protocol.length - 1) + '" as protocol instead of the "redis" protocol!');
39 }
40 }
41 if (parsed.pathname && parsed.pathname !== '/') {
42 options.db = parsed.pathname.substr(1);
43 }
44 if (parsed.hostname) {
45 options.host = parsed.hostname;
46 }
47 if (parsed.port) {
48 options.port = parsed.port;
49 }
50 if (parsed.search !== '') {
51 var elem;
52 for (elem in parsed.query) {
53 // If options are passed twice, only the parsed options will be used
54 if (elem in options) {
55 if (options[elem] === parsed.query[elem]) {
56 console.warn('node_redis: WARNING: You passed the ' + elem + ' option twice!');
57 } else {
58 throw new RangeError('The ' + elem + ' option is added twice and does not match');
59 }
60 }
61 options[elem] = parsed.query[elem];
62 }
63 }
64 } else if (parsed.hostname) {
65 throw new RangeError('The redis url must begin with slashes "//" or contain slashes after the redis protocol');
66 } else {
67 options.path = url;
68 }
69
70 } else if (typeof port_arg === 'object' || port_arg === undefined) {
71 options = utils.clone(port_arg || options);
72 options.host = options.host || host_arg;
73
74 if (port_arg && arguments.length !== 1) {
75 throw new TypeError('Too many arguments passed to createClient. Please only pass the options object');
76 }
77 }
78
79 if (!options) {
80 throw new TypeError('Unknown type of connection in createClient()');
81 }
82
83 return options;
84};