File size: 1,309 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
import { public_conversation } from '@figuro/chatwoot-sdk';
import { ChatWootAPIConfig } from '@waha/apps/chatwoot/client/interfaces';
import * as NodeCache from 'node-cache';

import { IConversationCache } from './IConversationCache';

const cache: NodeCache = new NodeCache({
  stdTTL: 24 * 60 * 60, // 1 day
  useClones: false,
});

export function CacheForConfig(config: ChatWootAPIConfig): ConversationCache {
  return new ConversationCache(`${config.url}+${config.inboxId}`);
}

class ConversationCache implements IConversationCache {
  constructor(private prefix: string) {}

  fullKey(key: string) {
    return `${this.prefix}.${key}`;
  }

  delete(key: string): void {
    const fullKey = this.fullKey(key);
    cache.del(fullKey);
  }

  get(key: string): public_conversation | null {
    const fullKey = this.fullKey(key);
    return cache.get(fullKey) || null;
  }

  has(key: string): boolean {
    const fullKey = this.fullKey(key);
    return cache.has(fullKey);
  }

  set(key: string, value: public_conversation): void {
    const fullKey = this.fullKey(key);
    cache.set(fullKey, value);
  }

  /**
   * Completely clean the cache with the prefix
   */
  clean() {
    cache.keys().forEach((key) => {
      if (key.startsWith(this.prefix)) {
        cache.del(key);
      }
    });
  }
}