aboutsummaryrefslogtreecommitdiff
path: root/src/shared/settings/Search.ts
blob: 7d7e55515992d5a71d0f2ce9928565d72535d79a (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
type Entries = { [name: string]: string };

export type SearchJSON = {
  default: string;
  engines: { [key: string]: string };
};

export default class Search {
  constructor(
    public defaultEngine: string,
    public engines: Entries,
  ) {
  }

  static fromJSON(json: SearchJSON): Search {
    for (let [name, url] of Object.entries(json.engines)) {
      if (!(/^[a-zA-Z0-9]+$/).test(name)) {
        throw new TypeError('Search engine\'s name must be [a-zA-Z0-9]+');
      }
      let matches = url.match(/{}/g);
      if (matches === null) {
        throw new TypeError(`No {}-placeholders in URL of "${name}"`);
      } else if (matches.length > 1) {
        throw new TypeError(`Multiple {}-placeholders in URL of "${name}"`);
      }
    }
    if (!Object.keys(json.engines).includes(json.default)) {
      throw new TypeError(`Default engine "${json.default}" not found`);
    }

    return new Search(json.default, json.engines);
  }

  toJSON(): SearchJSON {
    return {
      default: this.defaultEngine,
      engines: this.engines,
    };
  }
}