diff --git a/README.md b/README.md index 491b628..26d2fec 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Under the hood the official [redis](https://github.com/NodeRedis/node_redis) cli npm i fastify-redis --save ``` ## Usage -Add it to you project with `register` and you are done! +Add it to your project with `register` and you are done! You can access the *Redis* client via `fastify.redis`. If needed, you can pass a custom ``driver`` option, such as [ioredis](https://github.com/luin/ioredis). By default the official [redis](https://github.com/NodeRedis/node_redis) client is used. @@ -47,6 +47,20 @@ fastify.listen(3000, err => { }) ``` +You may also supply an existing *Redis* client instance by passing an options +object with the `client` property set to the instance. + +```js +const fastify = Fastify() +const redis = require('redis').createClient({host: 'localhost', port: 6379}) + +fastify.register(fastifyRedis, {client: redis}) + +// ... +// ... +// ... +``` + ## Acknowledgements This project is kindly sponsored by: diff --git a/index.js b/index.js index 18ebced..ad51b5e 100644 --- a/index.js +++ b/index.js @@ -4,14 +4,17 @@ const fp = require('fastify-plugin') const redis = require('redis') function fastifyRedis (fastify, options, next) { - var client = null - try { - // if custom redis module, default is redis. - const Driver = options.driver - delete options.driver - client = Driver ? new Driver(options) : redis.createClient(options) - } catch (err) { - return next(err) + var client = options.client || null + + if (!client) { + try { + // if custom redis module, default is redis. + const Driver = options.driver + delete options.driver + client = Driver ? new Driver(options) : redis.createClient(options) + } catch (err) { + return next(err) + } } fastify diff --git a/test.js b/test.js index e76986d..cf8b318 100644 --- a/test.js +++ b/test.js @@ -110,3 +110,26 @@ test('fastify.redis should be the redis client when use the custom redis driver' }) }) }) + +test('fastify.redis should be a singleton', t => { + t.plan(5) + const fastify = Fastify() + const redis = require('redis').createClient({host: 'localhost', port: 6379}) + + fastify.register(fastifyRedis, {client: redis}) + + fastify.ready(err => { + t.error(err) + t.is(fastify.redis, redis) + + fastify.redis.set('key', 'value', err => { + t.error(err) + fastify.redis.get('key', (err, val) => { + t.error(err) + t.equal(val, 'value') + + fastify.close() + }) + }) + }) +})