import axios, { AxiosResponse } from "axios"; import Token from "../lib/token"; export class ApiClient { readonly url = "http://localhost:3000/api"; token = new Token(); async authenticatedGet(path: string) { const request_url = `${ this.url }${ path }`; let request: any; let options = { headers: { Authorization: this.token.get() } }; request = await this.makeGetRequest(request_url, options); if(request.response) { // Let's try with a refreshed token. this.token.refresh() options = { headers: { Authorization: this.token.getRefresh() } }; 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 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]; } private async makeGetRequest(request_url: string, headers?: object) { try { const response = await axios.get(request_url, headers); return response } catch(error) { return error; } } }