summaryrefslogtreecommitdiff
path: root/app/infrastructure/api.js
blob: da8e8a59f083297db58bec80b0ec31b4019788ad (plain)
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
export default class Api {
  constructor(configuration, applicationStorage) {
    this.configuration = configuration;
    this.storage = applicationStorage;
  }

  get(relativeUrl, success) {
    const url = this.buildUrlFor(relativeUrl);
    this.defaultHeaders((headers) => {
      console.log(`GET ${url}`);
      this.execute(url, { method: 'GET', headers: headers }, success);
    });
  }

  post(relativeUrl, body, success) {
    const url = this.buildUrlFor(relativeUrl);
    this.defaultHeaders((headers) => {
      console.log(`POST ${url}`);
      this.execute(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(body)
      }, success);
    });
  }

  execute(url, options, success) {
    fetch(url, options)
      .then((response) => response.json())
      .then(success)
      .catch((error) => console.error(error))
      .done();
  }

  defaultHeaders(success) {
    this.storage
      .fetch('authentication_token')
      .then((token) => {
        success({
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        });
      })
      .catch((error) => console.error(error))
      .done();
  }

  buildUrlFor(url) {
    let host = this.configuration.value_for('API_HOST');
    return `${host}/api${url}`
  }
}