createClient.js 3.1 KB

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