summaryrefslogtreecommitdiff
path: root/src/clients/api_client.ts
blob: e544f162c6b7dc1632e36a3a2ab64dee5c2a57e3 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import axios, { AxiosResponse } from "axios";
import Token from "../lib/token";

export class ApiClient {
  readonly url = "http://localhost:3000/api";
  public readonly token = new Token();

  async authenticatedGet(path: string) {
    const request_url = `${ this.url }${ path }`;
    let request: any;
    let options = this.authorizationHeaders();
    
    request = await this.makeGetRequest(request_url, options);

    if(request.response) {
      // Let's try with a refreshed token.
      this.token.refresh()
      options = this.authorizationHeaders();
      request = await this.makeGetRequest(request_url, options);
    }

    return request;
  }

  async get(path: string) {
    const request_url = `${ this.url }${ path }`;
    const response = await this.makeGetRequest(request_url);

    return response;
  }

  async post(path: string, data: FormData, headers?: object) {
    const request_url = `${ this.url }${ path }`;
    const response = await axios.post(request_url, data, headers);

    return response;
  }

  async put(path: string, data: FormData) {
    const request_url = `${ this.url }${ path }`;
    const options = this.authorizationHeaders();

    const response = await axios.put(request_url, data, options);
    return response
  }

  async del(path: string) {
    const request_url = `${ this.url }${ path }`;
    const options = this.authorizationHeaders();

    const response = await axios.delete(request_url, options);
    return response;
  }

  async getProduct(id: string) {
    const request_url = `${ this.url }/products/${ id }`;
    const [product_response, product_reviews] = await Promise.all([
      this.makeGetRequest(request_url),
      this.makeGetRequest(`${ request_url }/reviews`)
    ]);

    return [product_response, product_reviews];
  }

  authorizationHeaders() {
    return {
      headers: {
        Authorization: `Bearer ${this.token.get()}`
      }
    };
  }

  private async makeGetRequest(request_url: string, headers?: object) {
    try {
      const response = await axios.get(request_url, headers);

      return response
    } catch(error) {
      return error;
    }
  }
}