Fix session memory leak

This commit is contained in:
Jonathan Cremin 2015-08-22 18:24:39 +01:00
parent 0289bddde8
commit 046d8475cb
6 changed files with 62 additions and 32 deletions

View file

@ -1,29 +1,59 @@
import redis from 'redis-url';
import coRedis from 'co-redis';
import koaRedis from 'koa-redis';
import session from 'koa-generic-session';
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) => {
const 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);
});
resolve(redis.connect(redisUrl));
}).catch((err) => {
debug('Promise error: ' + err);
debug('Connection error: ' + err);
});
export default function () {
return function* redisMiddleware(next) {
this.redis = yield connection;
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);
});
});
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);
});
});
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;
yield next;
}
}