hostr/lib/redis.js

59 lines
1.4 KiB
JavaScript
Raw Normal View History

2015-09-01 14:09:52 +02:00
import redis from 'redis';
2015-08-22 13:57:19 +01:00
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');
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-09-01 14:09:52 +02:00
const client = redis.createClient(process.env.REDIS_URL);
2015-08-23 22:12:32 +01:00
client.on('error', reject);
resolve(client);
2015-08-22 18:24:39 +01:00
}).catch((err) => {
2016-06-06 15:37:00 +01:00
debug('Connection error: ', err);
2015-08-23 22:12:32 +01:00
throw err;
2015-08-22 18:24:39 +01:00
});
2016-06-06 15:37:00 +01:00
const redisSession = new Promise((resolve, reject) =>
connection.then((client) => {
const sessionClient = koaRedis({ client });
2015-08-22 18:24:39 +01:00
resolve(session({
key: 'hid',
2015-08-23 22:12:32 +01:00
store: sessionClient,
2015-08-22 18:24:39 +01:00
}));
}).catch((err) => {
2016-06-06 15:37:00 +01:00
debug('koa-redis error: ', err);
2015-08-22 18:24:39 +01:00
reject(err);
2016-06-06 15:37:00 +01:00
})
);
2015-08-22 18:24:39 +01:00
2016-06-06 15:37:00 +01:00
const wrapped = new Promise((resolve, reject) =>
connection.then((client) => {
2015-08-23 22:12:32 +01:00
const asyncClient = coRedis(client);
asyncClient.on('error', reject);
asyncClient.on('ready', () => {
2015-08-22 18:24:39 +01:00
debug('Successfully connected to Redis');
2015-08-23 22:12:32 +01:00
resolve(asyncClient);
2015-08-22 18:24:39 +01:00
});
}).catch((err) => {
2016-06-06 15:37:00 +01:00
debug('co-redis error: ', err);
2015-08-22 18:24:39 +01:00
reject(err);
2015-08-23 22:12:32 +01:00
throw err;
2016-06-06 15:37:00 +01:00
})
);
2015-08-22 13:57:19 +01:00
2015-08-22 18:24:39 +01:00
export function sessionStore() {
2018-06-02 15:50:39 +00:00
return async (ctx, next) => {
const sess = await redisSession;
await sess.bind(ctx)(next());
2015-08-23 22:12:32 +01:00
};
2015-08-22 18:24:39 +01:00
}
export function middleware() {
2018-06-02 15:50:39 +00:00
return async (ctx, next) => {
ctx.redis = await wrapped;
await next();
2015-08-23 22:12:32 +01:00
};
2015-08-22 13:57:19 +01:00
}