Skip to content

Commit

Permalink
chore: self cache api requests with preferences
Browse files Browse the repository at this point in the history
  • Loading branch information
Yizack committed Jun 22, 2024
1 parent 3e60047 commit 20f0e45
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion utils/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
Expand Down
20 changes: 18 additions & 2 deletions utils/capacitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 20f0e45

Please sign in to comment.