From 8a2849fb74908169191de278cfab4ed86d075083 Mon Sep 17 00:00:00 2001 From: Qi He Date: Mon, 12 Sep 2016 17:47:58 -0700 Subject: [PATCH] redis options accepts url --- index.js | 30 ++++++++++++++++++++++++++---- test/caching-test.js | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index aa7c33e..4f2d1b6 100644 --- a/index.js +++ b/index.js @@ -6,10 +6,21 @@ const FIVE_MINUTES = 5 * 60; class RedisCache { constructor(options) { - let client = this.client = redis.createClient({ - host: options.host, - port: options.port - }); + var redisOptions = options; + + if (options.url) { + redisOptions = this._stripUsernameFromConfigUrl(options.url); + } else { + redisOptions = { + host: options.host, + port: options.port + }; + if (options.password) { + redisOptions.password = options.password; + } + } + + let client = this.client = redis.createClient(redisOptions); this.expiration = options.expiration || FIVE_MINUTES; this.connected = false; @@ -75,6 +86,17 @@ class RedisCache { }); }); } + + _stripUsernameFromConfigUrl(configUrl) { + let regex = /redis:\/\/(\w+):(\w+)(.*)/; + let matches = configUrl.match(regex); + + if (matches) { + configUrl = 'redis://:' + matches[2] + matches[3]; + } + + return configUrl; + } } module.exports = RedisCache; diff --git a/test/caching-test.js b/test/caching-test.js index a54e8d8..488e282 100644 --- a/test/caching-test.js +++ b/test/caching-test.js @@ -62,6 +62,30 @@ describe('caching tests', function() { }); }); + describe('redis options tests', function() { + it('accepts redis password', function() { + cache = new RedisCache({ + host: "127.0.0.1", + port: "6379", + password: "some-password" + }); + expect(cache.client.options.host).to.equal('127.0.0.1'); + expect(cache.client.options.port).to.equal('6379'); + expect(cache.client.options.password).to.equal('some-password'); + }); + + it('uses redis url instead of host and port when url is provided', function() { + cache = new RedisCache({ + host: "127.0.0.1", + port: "6379", + url: "redis://some-user:some-password@some-host.com:1234" + }); + expect(cache.client.options.host).to.equal('some-host.com'); + expect(cache.client.options.port).to.equal('1234'); + expect(cache.client.options.password).to.equal('some-password'); + }); + }); + describe('custom keys tests', function() { beforeEach(function() { cache = new RedisCache({