master
 1export default class Api {
 2  constructor(configuration, applicationStorage) {
 3    this.configuration = configuration;
 4    this.storage = applicationStorage;
 5  }
 6
 7  get(relativeUrl, success) {
 8    const url = this.buildUrlFor(relativeUrl);
 9    this.defaultHeaders((headers) => {
10      console.log(`GET ${url}`);
11      this.execute(url, { method: 'GET', headers: headers }, success);
12    });
13  }
14
15  post(relativeUrl, body, success) {
16    const url = this.buildUrlFor(relativeUrl);
17    this.defaultHeaders((headers) => {
18      console.log(`POST ${url}`);
19      this.execute(url, {
20        method: "POST",
21        headers: headers,
22        body: JSON.stringify(body)
23      }, success);
24    });
25  }
26
27  execute(url, options, success) {
28    fetch(url, options)
29      .then((response) => response.json())
30      .then(success)
31      .catch((error) => console.error(error))
32      .done();
33  }
34
35  defaultHeaders(success) {
36    this.storage
37      .fetch('authentication_token')
38      .then((token) => {
39        success({
40          'Accept': 'application/json',
41          'Content-Type': 'application/json',
42          'Authorization': `Bearer ${token}`,
43        });
44      })
45      .catch((error) => console.error(error))
46      .done();
47  }
48
49  buildUrlFor(url) {
50    let host = this.configuration.value_for('API_HOST');
51    return `${host}/api${url}`
52  }
53}
54