From 385606ee05a8ceb9073169639eb1a311f81cac10 Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Thu, 11 May 2023 19:28:47 -0600 Subject: AƱade informaciĆ³n a la vista de usuario MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/clients/api_client.ts | 33 ++++++++++++++++++++++++++++++--- src/clients/loaders.ts | 15 +++++++-------- 2 files changed, 37 insertions(+), 11 deletions(-) (limited to 'src/clients') diff --git a/src/clients/api_client.ts b/src/clients/api_client.ts index 7d2cf34..fc2d361 100644 --- a/src/clients/api_client.ts +++ b/src/clients/api_client.ts @@ -1,11 +1,38 @@ -import axios from "axios"; +import axios, { AxiosResponse } from "axios"; +import Token from "../lib/token"; export class ApiClient { readonly url = "http://localhost:3000/api"; + token = new Token(); - async get(path: string, params?: URLSearchParams, headers?: object) { + async authenticatedGet(path: string) { const request_url = `${ this.url }${ path }`; - const response = await this.makeGetRequest(request_url, headers); + 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; } diff --git a/src/clients/loaders.ts b/src/clients/loaders.ts index 2af7770..d9972d5 100644 --- a/src/clients/loaders.ts +++ b/src/clients/loaders.ts @@ -12,17 +12,16 @@ export async function loader({ request }) { export async function accountLoader() { const client = new ApiClient(); - const token = new Token(); + + const account_response = await client.authenticatedGet("/account"); + const addresses_response = await client.authenticatedGet("/account/addresses"); + const cards_response = await client.authenticatedGet("/account/cards"); - if(!token.present()) + // Authentication error handling. + if(account_response.response || addresses_response.response || cards_response.response) return redirect("/products"); - const headers = { - "Authentication": `Bearer ${ token.get() }` - }; - - const response = await client.get("/account", undefined, headers); - return response; + return [account_response, addresses_response, cards_response]; } export async function productLoader({ params }) { -- cgit v1.2.3