Refactor Redis into middleware

This commit is contained in:
Jonathan Cremin 2015-08-22 13:57:19 +01:00
parent 0fea2d7158
commit 8474cca94c
4 changed files with 45 additions and 75 deletions

29
lib/redis.js Normal file
View file

@ -0,0 +1,29 @@
import redis from 'redis-url';
import coRedis from 'co-redis';
import debugname from 'debug';
const debug = debugname('hostr:redis');
const redisUrl = process.env.REDIS_URL || process.env.REDISTOGO_URL || 'redis://localhost:6379';
let connection = new Promise((resolve, reject) => {
debug('Connecting to Redis');
const client = redis.connect(redisUrl);
const wrapped = coRedis(client);
wrapped.client = client;
wrapped.on('error', (err) => {
debug('Client error: ' + err);
});
wrapped.on('ready', () => {
debug('Successfully connected to Redis');
resolve(wrapped);
});
}).catch((err) => {
debug('Promise error: ' + err);
});
export default function () {
return function* redisMiddleware(next) {
this.redis = yield connection;
yield next;
}
}