import ApplicationComponent from "../ApplicationComponent"; import {Express} from "express"; 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 { private redisClient?: RedisClient; private store?: Store; public async start(app: Express): Promise { this.redisClient = redis.createClient(config.get('redis.port'), config.get('redis.host'), { password: config.has('redis.password') ? config.get('redis.password') : undefined, }); this.redisClient.on('error', (err: any) => { Logger.error(err, 'An error occurred with redis.'); }); this.store = new RedisStore({ client: this.redisClient, prefix: config.get('redis.prefix') + '-session:', }); } public async stop(): Promise { 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; } }