diff --git a/sitio/src/routes/+page.server.ts b/sitio/src/routes/+page.server.ts index fb92f70..d6ec90e 100644 --- a/sitio/src/routes/+page.server.ts +++ b/sitio/src/routes/+page.server.ts @@ -3,20 +3,9 @@ import { db, schema } from "$lib/server/db"; const { precios } = schema; import { sql } from "drizzle-orm"; -let cache: null | { key: Date; data: { precios: Precios } } = null; +let cache: Promise<{ key: Date; data: { precios: Precios } }> = doQuery(); -type Precios = { - ean: string; - name: string | null; - imageUrl: string | null; -}[]; - -export const load: PageServerLoad = async ({ - params, -}): Promise<{ precios: Precios }> => { - if (cache && +new Date() < +cache.key + 1000 * 60 * 10) { - return cache.data; - } +async function doQuery() { const q = db .select({ ean: precios.ean, @@ -30,6 +19,25 @@ export const load: PageServerLoad = async ({ .limit(150); const res = await q; const data = { precios: res }; - cache = { key: new Date(), data }; - return data; + return { key: new Date(), data }; +} + +setInterval( + async () => { + const c = await doQuery(); + cache = Promise.resolve(c); + }, + 4 * 60 * 60 * 1000, +); + +type Precios = { + ean: string; + name: string | null; + imageUrl: string | null; +}[]; + +export const load: PageServerLoad = async ({ + params, +}): Promise<{ precios: Precios }> => { + return (await cache).data; };