swaf/src/components/RedisComponent.ts

101 lines
3.1 KiB
TypeScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
import ApplicationComponent from "../ApplicationComponent";
import {Express} from "express";
2020-04-22 15:52:17 +02:00
import redis, {RedisClient} from "redis";
import config from "config";
import {log} from "../Logger";
2020-04-22 15:52:17 +02:00
import session, {Store} from "express-session";
import connect_redis from "connect-redis";
2020-07-19 11:57:47 +02:00
import CacheProvider from "../CacheProvider";
2020-04-22 15:52:17 +02:00
const RedisStore = connect_redis(session);
export default class RedisComponent extends ApplicationComponent implements CacheProvider {
2020-04-22 15:52:17 +02:00
private redisClient?: RedisClient;
private store?: Store;
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,
});
this.redisClient.on('error', (err: Error) => {
log.error(err, 'An error occurred with redis.');
2020-04-22 15:52:17 +02:00
});
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> {
const redisClient = this.redisClient;
if (redisClient) {
await this.close('Redis connection', callback => redisClient.quit(callback));
2020-04-22 15:52:17 +02:00
}
}
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;
}
2020-07-19 11:57:47 +02:00
public async get<T extends string | undefined>(key: string, defaultValue?: T): Promise<T> {
return await new Promise<T>((resolve, reject) => {
2020-07-19 11:57:47 +02:00
if (!this.redisClient) {
reject(`Redis store was not initialized.`);
return;
}
this.redisClient.get(key, (err, val) => {
if (err) {
reject(err);
return;
}
resolve((val || defaultValue || undefined) as T);
2020-07-19 11:57:47 +02:00
});
});
}
public async has(key: string): Promise<boolean> {
return await this.get(key) !== undefined;
2020-07-19 11:57:47 +02:00
}
public async forget(key: string): Promise<void> {
return await new Promise<void>((resolve, reject) => {
2020-07-19 11:57:47 +02:00
if (!this.redisClient) {
reject(`Redis store was not initialized.`);
return;
}
this.redisClient.del(key, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
public async remember(key: string, value: string, ttl: number): Promise<void> {
return await new Promise<void>((resolve, reject) => {
2020-07-19 11:57:47 +02:00
if (!this.redisClient) {
reject(`Redis store was not initialized.`);
return;
}
this.redisClient.psetex(key, ttl, value, (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
}