Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 11 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
})
})