aboutsummaryrefslogtreecommitdiff
path: root/src/settings/actions/setting.ts
blob: b03cd80132b0a3d1dbe55374c557f945ab9ae221 (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
import * as actions from './index';
import * as validator from '../../shared/settings/validator';
import * as settingsValues from '../../shared/settings/values';
import * as settingsStorage from '../../shared/settings/storage';
import keymaps from '../keymaps';

const load = async(): Promise<actions.SettingAction> => {
  let settings = await settingsStorage.loadRaw();
  return set(settings);
};

const save = async(settings: any): Promise<actions.SettingAction> => {
  try {
    if (settings.source === 'json') {
      let value = JSON.parse(settings.json);
      validator.validate(value);
    }
  } catch (e) {
    return {
      type: actions.SETTING_SHOW_ERROR,
      error: e.toString(),
      json: settings.json,
    };
  }
  await settingsStorage.save(settings);
  return set(settings);
};

const switchToForm = (json: string): actions.SettingAction => {
  try {
    validator.validate(JSON.parse(json));
    let form = settingsValues.formFromJson(json, keymaps.allowedOps);
    return {
      type: actions.SETTING_SWITCH_TO_FORM,
      form,
    };
  } catch (e) {
    return {
      type: actions.SETTING_SHOW_ERROR,
      error: e.toString(),
      json,
    };
  }
};

const switchToJson = (form: any): actions.SettingAction => {
  let json = settingsValues.jsonFromForm(form);
  return {
    type: actions.SETTING_SWITCH_TO_JSON,
    json,
  };
};

const set = (settings: any): actions.SettingAction => {
  return {
    type: actions.SETTING_SET_SETTINGS,
    source: settings.source,
    json: settings.json,
    form: settings.form,
  };
};

export { load, save, set, switchToForm, switchToJson };