Skip to content

Commit

Permalink
core: Use ioredis instead to support native async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
Atinux committed Jan 19, 2018
1 parent d3aab0c commit 7cbb20e
Show file tree
Hide file tree
Showing 7 changed files with 255 additions and 88 deletions.
Binary file modified .DS_Store
Binary file not shown.
18 changes: 5 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ module.exports = {
mono: {
redis: {
port: 8047,
// See https://github.com/NodeRedis/node_redis#options-object-properties for more argument
// See [options] of https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options
}
}
}
Expand All @@ -45,17 +45,9 @@ In your modules files, you can access `redis` instance like this:
```js
const { redis } = require('mono-redis')

redis.set('key', 'value', () => { console.log('value setted') })
redis.get('key', (value) => { console.log(`value is ${value}`)})

await redis.set('hello', 'world!')
const hello = await redis.get('hello')
// hello = 'world!'
```

The current functions of redis client are using callback function but you can convert it to async function with the mono utils

```js
const { redis } = require('mono-redis')
const { cb } = require('@terrajs/mono/utils')

await cb(redis.set.bind(redis), 'key', 'value')
const result = await cb(redis.get.bind(redis))
```
We are using [ioredis](https://github.com/luin/ioredis) as a client since it supports async/await promises.
20 changes: 14 additions & 6 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
const redis = require('redis')
const Redis = require('ioredis')

// Promosify methods
// redis.RedisClient.prototype = pify(redis.RedisClient.prototype, { excludeMain: true })

module.exports = async function ({ conf, log }) {
const redisConfig = conf.mono.redis || {}

log.info(`Opening Redis connection...`)
let redisClient = redis.createClient(redisConfig)
// See [options] of https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options
let redis = new Redis(redisConfig)

// Expose redis client
module.exports.redis = redisClient
// Expose redis client (promisifed)
module.exports.redis = redis

// Bind connect and error connection
return new Promise((resolve, reject) => {
redisClient.on('error', (err) => {
redis.on('error', (err) => {
log.error('Could not connect to Redis server')
/* istanbul ignore else */
if (err.code === 'ECONNREFUSED') {
reject(new Error(`Redis connection to ${err.address}:${err.port} failed`))
}
reject(err)
})

redisClient.on('connect', () => {
redis.on('ready', () => {
log.info(`Redis connected`)
resolve()
})
Expand Down

0 comments on commit 7cbb20e

Please sign in to comment.