sitio: precachear query index

This commit is contained in:
Cat /dev/Nulo 2024-01-23 00:06:13 -03:00
parent fe63599e0e
commit eb2b68fab0

View file

@ -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;
};