From a9b44cbae79e9c01cff07964a45e1c7efa7fb241 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Thu, 5 Dec 2024 19:20:36 -0800 Subject: cached rates --- src/lib/cache.ts | 17 +++++++++++++++++ src/lib/invoice.ts | 5 +++-- src/lib/rates.ts | 13 +++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 src/lib/cache.ts create mode 100644 src/lib/rates.ts (limited to 'src/lib') diff --git a/src/lib/cache.ts b/src/lib/cache.ts new file mode 100644 index 00000000..079c561b --- /dev/null +++ b/src/lib/cache.ts @@ -0,0 +1,17 @@ + +// src/lib/server/cache.ts +let cachedData: any = null; + +async function fetchData() { + // Fetch data from your API + const response = await fetch('https://api.example.com/data'); + cachedData = await response.json(); +} + +// Initialize cache and set up periodic updates +fetchData(); // Initial fetch +setInterval(fetchData, 60000); // Update every 60 seconds + +export function getCachedData() { + return cachedData; +} diff --git a/src/lib/invoice.ts b/src/lib/invoice.ts index a48e02a4..d7576e82 100644 --- a/src/lib/invoice.ts +++ b/src/lib/invoice.ts @@ -1,12 +1,13 @@ -import { auth, get, post } from "$lib/utils"; +import getRates from "$lib/rates"; +import { auth, post } from "$lib/utils"; import { redirect } from "@sveltejs/kit"; export default async ({ cookies, request }) => { const form = await request.formData(); const aid = form.get("aid") || cookies.get("aid"); - const rates = await get("/rates"); const amount = parseInt(form.get("amount")); + const rates = await getRates(); let invoice = { aid, diff --git a/src/lib/rates.ts b/src/lib/rates.ts new file mode 100644 index 00000000..96aaeac2 --- /dev/null +++ b/src/lib/rates.ts @@ -0,0 +1,13 @@ +import { get } from "$lib/utils"; + +let last; +let rates; + +export default async function getRates() { + if (!rates || Date.now() - last > 60000) { + rates = await get("/rates"); + last = Date.now(); + } + + return rates; +} -- cgit v1.2.3