Untitled
unknown
plain_text
a year ago
1.5 kB
13
Indexable
import { error } from '@sveltejs/kit';
import { db } from '$db';
import { listingsTable, cpuModelsTable, suppliersTable } from '$db/schema';
import { eq, lte } from 'drizzle-orm';
import type { PageServerLoad } from './$types';
const DEFAULT_BUDGET = 800;
const CENTS_PER_EURO = 100;
const getListingsQuery = (budget: number) =>
db
.select({
id: listingsTable.id,
name: cpuModelsTable.name,
price: listingsTable.price,
shippingCost: listingsTable.shippingCost,
supplier: suppliersTable.name,
url: listingsTable.url
})
.from(listingsTable)
.innerJoin(cpuModelsTable, eq(listingsTable.cpuModelId, cpuModelsTable.id))
.innerJoin(suppliersTable, eq(listingsTable.supplierId, suppliersTable.id))
.where(lte(listingsTable.price, budget * CENTS_PER_EURO))
.orderBy(listingsTable.price);
const convertCentsToEuros = (cents: number) => cents / CENTS_PER_EURO;
export const load: PageServerLoad = async ({ url }) => {
const budget = Number(url.searchParams.get('budget')) || DEFAULT_BUDGET;
try {
const listings = await getListingsQuery(budget);
return {
listings: listings.map((listing) => ({
...listing,
price: convertCentsToEuros(listing.price),
shippingCost: convertCentsToEuros(listing.shippingCost)
}))
};
} catch (err) {
console.error('Error fetching listings:', err);
throw error(500, 'An error occurred while fetching listings');
}
};
Editor is loading...
Leave a Comment