Skip to content

Commit c042182

Browse files
authored
Add option to close passed in client (#66)
1 parent 837d0fc commit c042182

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

README.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,17 @@ const fastify = require('fastify')()
5656
const redis = require('redis').createClient({ host: 'localhost', port: 6379 })
5757

5858
fastify.register(require('fastify-redis'), { client: redis })
59+
```
60+
61+
Note: by default, *fastify-redis* will **not** automatically close the client
62+
connection when the Fastify server shuts down. To opt-in to this behavior,
63+
register the client like so:
5964

60-
// ...
61-
// ...
62-
// ...
65+
```js
66+
fastify.register(require('fastify-redis'), {
67+
client: redis,
68+
closeClient: true
69+
})
6370
```
6471

6572
## Registering multiple Redis client instances

index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ function fastifyRedis (fastify, options, next) {
5555
}
5656

5757
fastify.decorate('redis', client)
58+
if (options.closeClient === true) {
59+
fastify.addHook('onClose', close)
60+
}
5861
}
5962
}
6063

test/test.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,37 @@ test('custom client', (t) => {
181181
})
182182
})
183183

184+
test('custom client gets closed', (t) => {
185+
t.plan(7)
186+
const fastify = Fastify()
187+
const redis = require('redis').createClient({ host: 'localhost', port: 6379 })
188+
189+
fastify.register(fastifyRedis, { client: redis, closeClient: true })
190+
191+
fastify.ready((err) => {
192+
t.error(err)
193+
t.is(fastify.redis, redis)
194+
195+
fastify.redis.set('key', 'value', (err) => {
196+
t.error(err)
197+
fastify.redis.get('key', (err, val) => {
198+
t.error(err)
199+
t.equal(val, 'value')
200+
201+
const origQuit = fastify.redis.quit
202+
fastify.redis.quit = (cb) => {
203+
t.pass('redis client closed')
204+
origQuit.call(fastify.redis, cb)
205+
}
206+
207+
fastify.close(function (err) {
208+
t.error(err)
209+
})
210+
})
211+
})
212+
})
213+
})
214+
184215
test('custom client inside a namespace', (t) => {
185216
t.plan(7)
186217
const fastify = Fastify()

0 commit comments

Comments
 (0)