aboutsummaryrefslogtreecommitdiff
path: root/src/background/usecases/SettingUseCase.ts
blob: 07f0d7cf279ecc7da3b96311719a582995194394 (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
import { inject, injectable } from "tsyringe";
import CachedSettingRepository from "../repositories/CachedSettingRepository";
import SettingData, { DefaultSettingData } from "../../shared/SettingData";
import Settings from "../../shared/settings/Settings";
import Notifier from "../presenters/Notifier";
import SettingRepository from "../repositories/SettingRepository";

@injectable()
export default class SettingUseCase {
  constructor(
    @inject("LocalSettingRepository")
    private localSettingRepository: SettingRepository,
    @inject("SyncSettingRepository")
    private syncSettingRepository: SettingRepository,
    @inject("CachedSettingRepository")
    private cachedSettingRepository: CachedSettingRepository,
    @inject("Notifier") private notifier: Notifier
  ) {}

  getCached(): Promise<Settings> {
    return this.cachedSettingRepository.get();
  }

  async reload(): Promise<Settings> {
    let data = DefaultSettingData;
    try {
      data = await this.loadSettings();
    } catch (e) {
      this.showUnableToLoad(e);
    }

    let value: Settings;
    try {
      value = data.toSettings();
    } catch (e) {
      this.showUnableToLoad(e);
      value = DefaultSettingData.toSettings();
    }
    await this.cachedSettingRepository.update(value!);
    return value;
  }

  private async loadSettings(): Promise<SettingData> {
    const sync = await this.syncSettingRepository.load();
    if (sync) {
      return sync;
    }
    const local = await this.localSettingRepository.load();
    if (local) {
      return local;
    }
    return DefaultSettingData;
  }

  private showUnableToLoad(e: Error) {
    console.error("unable to load settings", e);
    this.notifier.notifyInvalidSettings(e, () => {
      browser.runtime.openOptionsPage();
    });
  }
}