aboutsummaryrefslogtreecommitdiff
path: root/src/background/repositories/SettingRepository.ts
blob: d726cfb9ab9bae98c28d919450630ee7b3bb59cf (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
import SettingData from "../../shared/SettingData";

export default interface SettingRepository {
  load(): Promise<SettingData | null>;

  onChange(callback: () => void): void;
}

export class LocalSettingRepository implements SettingRepository {
  async load(): Promise<SettingData | null> {
    const { settings } = await browser.storage.local.get("settings");
    if (!settings) {
      return null;
    }
    return SettingData.fromJSON(settings as any);
  }

  onChange(callback: () => void) {
    browser.storage.onChanged.addListener((changes, area) => {
      if (area !== "local") {
        return;
      }
      if (changes.settings) {
        callback();
      }
    });
  }
}

export class SyncSettingRepository implements SettingRepository {
  async load(): Promise<SettingData | null> {
    const { settings } = await browser.storage.sync.get("settings");
    if (!settings) {
      return null;
    }
    return SettingData.fromJSON(settings as any);
  }

  onChange(callback: () => void) {
    browser.storage.onChanged.addListener((changes, area) => {
      if (area !== "sync") {
        return;
      }
      if (changes.settings) {
        callback();
      }
    });
  }
}