aboutsummaryrefslogtreecommitdiff
path: root/src/background/usecases/SettingUseCase.ts
blob: bd61157577cdf6f78a9737c0e52d5f1a63960208 (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
import { injectable } from 'tsyringe';
import LocalSettingRepository from '../repositories/LocalSettingRepository';
import CachedSettingRepository from '../repositories/CachedSettingRepository';
import { DefaultSettingData } from '../../shared/SettingData';
import Settings from '../../shared/settings/Settings';
import NotifyPresenter from '../presenters/NotifyPresenter';

@injectable()
export default class SettingUseCase {

  constructor(
    private localSettingRepository: LocalSettingRepository,
    private cachedSettingRepository: CachedSettingRepository,
    private notifyPresenter: NotifyPresenter,
  ) {
  }

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

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

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

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