2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
2020-07-11 11:46:16 +02:00
|
|
|
import {Express} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
import redis, {RedisClient} from "redis";
|
|
|
|
import config from "config";
|
|
|
|
import Logger from "../Logger";
|
|
|
|
import session, {Store} from "express-session";
|
|
|
|
import connect_redis from "connect-redis";
|
|
|
|
|
|
|
|
const RedisStore = connect_redis(session);
|
|
|
|
|
|
|
|
export default class RedisComponent extends ApplicationComponent<void> {
|
|
|
|
private redisClient?: RedisClient;
|
|
|
|
private store?: Store;
|
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async start(app: Express): Promise<void> {
|
2020-04-25 18:31:54 +02:00
|
|
|
this.redisClient = redis.createClient(config.get('redis.port'), config.get('redis.host'), {
|
|
|
|
password: config.has('redis.password') ? config.get<string>('redis.password') : undefined,
|
|
|
|
});
|
2020-04-22 15:52:17 +02:00
|
|
|
this.redisClient.on('error', (err: any) => {
|
|
|
|
Logger.error(err, 'An error occurred with redis.');
|
|
|
|
});
|
|
|
|
this.store = new RedisStore({
|
|
|
|
client: this.redisClient,
|
2020-04-25 09:32:59 +02:00
|
|
|
prefix: config.get<string>('redis.prefix') + '-session:',
|
2020-04-22 15:52:17 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public async stop(): Promise<void> {
|
|
|
|
if (this.redisClient) {
|
|
|
|
await this.close('Redis connection', this.redisClient, this.redisClient.quit);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public getStore(): Store {
|
|
|
|
if (!this.store) throw `Redis store was not initialized.`;
|
|
|
|
return this.store;
|
|
|
|
}
|
|
|
|
|
|
|
|
public canServe(): boolean {
|
|
|
|
return this.redisClient !== undefined && this.redisClient.connected;
|
|
|
|
}
|
|
|
|
}
|