Socialify

Folder ..

Viewing cache.ts
50 lines (41 loc) • 1.3 KB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { config } from "dotenv";
import { Redis } from "ioredis";

config();

export class AniwatchAPICache {
  private _client: Redis | null;
  public isOptional: boolean = true;

  static DEFAULT_CACHE_EXPIRY_SECONDS = 60 as const;
  static CACHE_EXPIRY_HEADER_NAME = "X-ANIWATCH-CACHE-EXPIRY" as const;

  constructor() {
    const redisConnURL = process.env?.ANIWATCH_API_REDIS_CONN_URL;
    this.isOptional = !Boolean(redisConnURL);
    this._client = this.isOptional ? null : new Redis(String(redisConnURL));
  }

  set(key: string | Buffer, value: string | Buffer | number) {
    if (this.isOptional) return;
    return this._client?.set(key, value);
  }

  get(key: string | Buffer) {
    if (this.isOptional) return;
    return this._client?.get(key);
  }

  /**
   * @param expirySeconds set to 60 by default
   */
  async getOrSet<T>(
    key: string | Buffer,
    setCB: () => Promise<T>,
    expirySeconds: number = AniwatchAPICache.DEFAULT_CACHE_EXPIRY_SECONDS
  ) {
    const cachedData = this.isOptional
      ? null
      : (await this._client?.get(key)) || null;
    let data = JSON.parse(String(cachedData)) as T;

    if (!data) {
      data = await setCB();
      await this._client?.set(key, JSON.stringify(data), "EX", expirySeconds);
    }
    return data;
  }
}

export const cache = new AniwatchAPICache();