From 20f0e457cafde68d76d9c844486e1d9bbc45266c Mon Sep 17 00:00:00 2001 From: Yizack Rangel Date: Sat, 22 Jun 2024 01:10:59 -0500 Subject: [PATCH] chore: self cache api requests with preferences --- utils/api.js | 2 +- utils/capacitor.js | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/utils/api.js b/utils/api.js index 13bff49..dde552f 100644 --- a/utils/api.js +++ b/utils/api.js @@ -37,7 +37,7 @@ class SaldometrobusAPI { } async getTarjetaAPI (numero) { - const { tarjeta, status, error, error_key } = await CAPACITOR.doGet(`${this.tarjetasAPI}/${numero}`); + const { tarjeta, status, error, error_key } = await CAPACITOR.doGet(`${this.tarjetasAPI}/${numero}`, true); if (!error && status === "ok" && tarjeta) { return { tarjeta }; } diff --git a/utils/capacitor.js b/utils/capacitor.js index 25b65db..4083fbd 100644 --- a/utils/capacitor.js +++ b/utils/capacitor.js @@ -52,9 +52,25 @@ class CapacitorPlugins { return status.connected; } - async doGet (url) { - const GET = CapacitorHttp.get({ url }).then((response) => { + async doGet (url, cached = false) { + const numero = new URL(url).pathname.split("/").pop(); + const cachedResponse = JSON.parse((await Preferences.get({ key: numero })).value); + + const currentTime = new Date().getTime(); + if (cached && cachedResponse && cachedResponse.expires && currentTime < cachedResponse.expires) { + return { + error: true, + error_key: `${t("tarjeta_actualizada")}: ${numero}` + }; + } + + const GET = CapacitorHttp.get({ url, headers: { "Cache-Control": "max-age=900" } }).then(async (response) => { if (response.status === 200) { + if (parseInt(numero)) { + const maxAge = parseInt(response.headers["Cache-Control"].split("=")[1]); + const expiresTime = currentTime + (maxAge * 1000); + await Preferences.set({ key: numero, value: JSON.stringify({ expires: expiresTime }) }); + } return response.data; } else {