From eb2b68fab0a9bda212c455220f885183a705e7ad Mon Sep 17 00:00:00 2001 From: Nulo Date: Tue, 23 Jan 2024 00:06:13 -0300 Subject: [PATCH] sitio: precachear query index --- sitio/src/routes/+page.server.ts | 38 +++++++++++++++++++------------- 1 file changed, 23 insertions(+), 15 deletions(-) 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; };