TipiCache.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { createClient, RedisClientType } from 'redis';
  2. import { getConfig } from '../core/config/TipiConfig';
  3. const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
  4. class TipiCache {
  5. private static instance: TipiCache;
  6. private client: RedisClientType;
  7. constructor() {
  8. const client = createClient({
  9. url: `redis://${getConfig().REDIS_HOST}:6379`,
  10. });
  11. this.client = client as RedisClientType;
  12. }
  13. public static getInstance(): TipiCache {
  14. if (!TipiCache.instance) {
  15. TipiCache.instance = new TipiCache();
  16. }
  17. return TipiCache.instance;
  18. }
  19. private async getClient(): Promise<RedisClientType> {
  20. if (!this.client.isOpen) {
  21. await this.client.connect();
  22. }
  23. return this.client;
  24. }
  25. public async set(key: string, value: string, expiration = ONE_DAY_IN_SECONDS) {
  26. const client = await this.getClient();
  27. return client.set(key, value, {
  28. EX: expiration,
  29. });
  30. }
  31. public async get(key: string) {
  32. const client = await this.getClient();
  33. return client.get(key);
  34. }
  35. public async del(key: string) {
  36. const client = await this.getClient();
  37. return client.del(key);
  38. }
  39. public async close() {
  40. return this.client.quit();
  41. }
  42. public async ttl(key: string) {
  43. const client = await this.getClient();
  44. return client.ttl(key);
  45. }
  46. }
  47. export default TipiCache.getInstance();