aboutsummaryrefslogtreecommitdiff
path: root/src/shared/settings/Search.ts
blob: bdbe4a83dea07d190d11147b71b0f20d2396b6ee (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
import Validator from './Validator';

const Schema = {
  type: 'object',
  properties: {
    default: { type: 'string' },
    engines: {
      type: 'object',
      propertyNames: {
        pattern: '^[A-Za-z_][A-Za-z0-9_]+$',
      },
      patternProperties: {
        '.*': { type: 'string' },
      },
    },
  },
  required: ['default'],
};

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: unknown): Search {
    let obj = new Validator<SearchJSON>(Schema).validate(json);

    for (let [name, url] of Object.entries(obj.engines)) {
      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(obj.engines).includes(obj.default)) {
      throw new TypeError(`Default engine "${obj.default}" not found`);
    }

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

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