hostr/lib/redis.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-08-22 13:57:19 +01:00
import redis from 'redis-url';
import coRedis from 'co-redis';
2015-08-22 18:24:39 +01:00
import koaRedis from 'koa-redis';
import session from 'koa-generic-session';
2015-08-22 13:57:19 +01:00
import debugname from 'debug';
const debug = debugname('hostr:redis');
const redisUrl = process.env.REDIS_URL || process.env.REDISTOGO_URL || 'redis://localhost:6379';
2015-08-22 18:24:39 +01:00
const connection = new Promise((resolve, reject) => {
2015-08-22 13:57:19 +01:00
debug('Connecting to Redis');
2015-08-22 18:24:39 +01:00
resolve(redis.connect(redisUrl));
}).catch((err) => {
debug('Connection error: ' + err);
});
const redisSession = new Promise((resolve, reject) => {
return connection.then((client) => {
client = koaRedis({client: client});
resolve(session({
key: 'hid',
store: client
}));
}).catch((err) => {
debug('koa-redis error: ' + err);
reject(err);
2015-08-22 13:57:19 +01:00
});
2015-08-22 18:24:39 +01:00
});
const wrapped = new Promise((resolve, reject) => {
return connection.then((client) => {
client = coRedis(client);
client.on('error', (err) => {
debug('Client error: ' + err);
reject(err);
});
client.on('ready', () => {
debug('Successfully connected to Redis');
resolve(client);
});
}).catch((err) => {
debug('co-redis error: ' + err);
reject(err);
2015-08-22 13:57:19 +01:00
});
});
2015-08-22 18:24:39 +01:00
export function sessionStore() {
return function* (next) {
const sess = yield redisSession;
yield sess.bind(this)(next);
}
}
export function middleware() {
return function* (next) {
this.redis = yield wrapped;
2015-08-22 13:57:19 +01:00
yield next;
}
}