Skip to content

Commit e15d992

Browse files
authored
feat: support redis connection url (#45)
1 parent 8ea385c commit e15d992

File tree

5 files changed

+40
-2
lines changed

5 files changed

+40
-2
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ jspm_packages
3232

3333
# Optional npm cache directory
3434
.npm
35+
package-lock.json
3536

3637
# Optional REPL history
3738
.node_repl_history

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ automatically closed when the fastify instance is closed.
2121
const fastify = require('fastify')()
2222

2323
fastify.register(require('fastify-redis'), { host: '127.0.0.1' })
24+
// or
25+
fastify.register(require('fastify-redis'), { url: 'redis://127.0.0.1', /* other redis options */ })
2426

2527
fastify.get('/foo', (req, reply) => {
2628
const { redis } = fastify

index.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ const Redis = require('ioredis')
66
function fastifyRedis (fastify, options, next) {
77
const namespace = options.namespace
88
delete options.namespace
9+
let redisUrl
10+
if (options.url) {
11+
redisUrl = options.url
12+
delete options.url
13+
}
914

1015
let client = options.client || null
1116

@@ -24,7 +29,11 @@ function fastifyRedis (fastify, options, next) {
2429

2530
if (!client) {
2631
try {
27-
client = new Redis(options)
32+
if (redisUrl) {
33+
client = new Redis(redisUrl, options)
34+
} else {
35+
client = new Redis(options)
36+
}
2837
} catch (err) {
2938
return next(err)
3039
}

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
"description": "Plugin to share a common Redis connection across Fastify.",
55
"main": "index.js",
66
"scripts": {
7-
"test": "standard && tap test.js",
7+
"test": "npm run lint && npm run unit",
8+
"lint": "standard",
9+
"unit": "tap test.js",
810
"redis": "docker run -p 6379:6379 --rm redis:5"
911
},
1012
"repository": {

test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,30 @@ test('fastify.redis should exist', (t) => {
3737
})
3838
})
3939

40+
test('fastify.redis should support url', (t) => {
41+
t.plan(4)
42+
const fastify = Fastify()
43+
44+
fastify.register(fastifyRedis, {
45+
url: 'redis://127.0.0.1',
46+
otherOption: 'foo'
47+
})
48+
49+
fastify.ready((err) => {
50+
t.error(err)
51+
52+
fastify.redis.set('key', 'value', (err) => {
53+
t.error(err)
54+
fastify.redis.get('key', (err, val) => {
55+
t.error(err)
56+
t.equal(val, 'value')
57+
58+
fastify.close()
59+
})
60+
})
61+
})
62+
})
63+
4064
test('fastify.redis should be the redis client', (t) => {
4165
t.plan(4)
4266
const fastify = Fastify()

0 commit comments

Comments
 (0)