aboutsummaryrefslogtreecommitdiff
path: root/src/background/repositories/ReadyFrameRepository.ts
blob: aa5d986d936cd7a1d91f0af1d4dca6b4b9932777 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
import MemoryStorage from "../infrastructures/MemoryStorage";

const REPOSITORY_KEY = "readyFrameRepository";

type State = { [tabId: number]: number[] };

export default interface ReadyFrameRepository {
  clearFrameIds(tabId: number): Promise<void>;

  addFrameId(tabId: number, frameId: number): Promise<void>;

  removeFrameId(tabId: number, frameId: number): Promise<void>;

  getFrameIds(tabId: number): Promise<number[] | undefined>;
}

export class ReadyFrameRepositoryImpl implements ReadyFrameRepository {
  private cache: MemoryStorage;

  constructor() {
    this.cache = new MemoryStorage();
  }

  clearFrameIds(tabId: number): Promise<void> {
    let state: State | undefined = this.cache.get(REPOSITORY_KEY);
    if (typeof state === "undefined") {
      state = {};
    }
    delete state[tabId];
    this.cache.set(REPOSITORY_KEY, state);
    return Promise.resolve();
  }

  addFrameId(tabId: number, frameId: number): Promise<void> {
    let state: State | undefined = this.cache.get(REPOSITORY_KEY);
    if (typeof state === "undefined") {
      state = {};
    }
    state[tabId] = (state[tabId] || []).concat(frameId).sort();
    this.cache.set(REPOSITORY_KEY, state);
    return Promise.resolve();
  }

  removeFrameId(tabId: number, frameId: number): Promise<void> {
    const state: State | undefined = this.cache.get(REPOSITORY_KEY);
    if (typeof state === "undefined") {
      return Promise.resolve();
    }
    const ids = state[tabId];
    if (typeof ids === "undefined") {
      return Promise.resolve();
    }
    state[tabId] = ids.filter((id) => id != frameId);
    this.cache.set(REPOSITORY_KEY, state);
    return Promise.resolve();
  }

  getFrameIds(tabId: number): Promise<number[] | undefined> {
    const state: State | undefined = this.cache.get(REPOSITORY_KEY);
    if (typeof state === "undefined") {
      return Promise.resolve(undefined);
    }
    return Promise.resolve(state[tabId]);
  }
}