Skip to content

Commit

Permalink
Upgrade database cashing
Browse files Browse the repository at this point in the history
  • Loading branch information
nomideusz committed Apr 8, 2024
1 parent 4613462 commit 04f5564
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 40 deletions.
4 changes: 0 additions & 4 deletions local_env_template

This file was deleted.

16 changes: 16 additions & 0 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const api = (customFetch = fetch) => ({
getAllAds: async () => {
const response = await customFetch(
'api',
)
const data = (await response.json())
return data
},
getAdsByCategory: async (cat: string) => {
const response = await customFetch(
`api?category=${cat}`,
)
const data = (await response.json())
return data
},
})
12 changes: 8 additions & 4 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@
import { onMount } from "svelte"
import { createQuery, useQueryClient } from "@tanstack/svelte-query"
import { subscribeToAds } from "$lib/supabase/subscribeToAds"
import { fetchAdsForCategories } from "./api/helpers"
import { api } from "$lib/api"
import { WebsiteName } from "../config"
import logo from "$lib/img/zaur.png?enhanced&w=373"
import { Button } from "bits-ui"
let queryClient = useQueryClient()
const categories = ["rental", "sales"]
$: ads = createQuery({
queryKey: ["ads", ...categories], // Rozwinięcie tablicy kategorii do klucza zapytania
queryFn: () => fetchAdsForCategories(...categories),
$: ads_sales = createQuery({
queryKey: ["ads", "sales"], // Rozwinięcie tablicy kategorii do klucza zapytania
queryFn: () => api(fetch).getAllAds()
})
$: ads_rental = createQuery({
queryKey: ["ads", "rental"], // Rozwinięcie tablicy kategorii do klucza zapytania
queryFn: () => api(fetch).getAdsByCategory('rental')
})
onMount(() => {
Expand Down
18 changes: 5 additions & 13 deletions src/routes/+page.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import { fetchAdsForCategories } from './api/helpers.js';
import { api } from "$lib/api";

export async function load({ fetch, parent }) {
export async function load({ parent, fetch, params, route }) {
const { queryClient } = await parent();

// Cachowanie danych dla 'sales'
await queryClient.prefetchQuery({
queryKey: ['ads', 'sales'],
queryFn: () => fetchAdsForCategories('sales', { fetch }),
queryKey: ['ads', route.id],
queryFn: () => api(fetch).getAdsByCategory('rental')
});

// Cachowanie danych dla 'rental'
await queryClient.prefetchQuery({
queryKey: ['ads', 'rental'],
queryFn: () => fetchAdsForCategories('rental', { fetch }),
});
}


}
40 changes: 23 additions & 17 deletions src/routes/api/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,34 @@ const categoryToTableMap = {
// Dodaj tutaj więcej kategorii w przyszłości
};

async function fetchDataForCategory(category) {
const tableName = categoryToTableMap[category];
if (!tableName) {
throw new Error('Invalid category provided');
}
const response = await supabase.from(tableName).select('*').order('created_at', { ascending: false }).range(0, 9);
return response.data; // Zakładamy, że 'response.data' zawiera potrzebne dane
}

export async function GET({ url }) {
const category = url.searchParams.get('category');

try {
// Obsługa zapytania dla wszystkich kategorii
if (category === '/') {
const responses = await Promise.all(Object.values(categoryToTableMap).map(tableName =>
supabase.from(tableName).select('*').order('created_at', { ascending: false }).range(0, 9)
));

const combinedResponse = responses.flatMap(response => response.data);
return json(combinedResponse);
if (category) {
// Logika dla pojedynczej kategorii, gdy parametr jest obecny
const data = await fetchDataForCategory(category);
return json({ [category]: data });
} else {
// Sprawdzenie, czy kategoria odpowiada znanej tabeli
const tableName = categoryToTableMap[category];
if (!tableName) {
return json({ error: 'Invalid category provided' }, { status: 400 });
}

// Logika dla pojedynczej kategorii
const response = await supabase.from(tableName).select('*').order('created_at', { ascending: false }).range(0, 9);
return json(response.data);
// Pobieranie danych dla obu kategorii jednocześnie, gdy parametr nie jest obecny
const [salesData, rentalData] = await Promise.all([
fetchDataForCategory('sales'),
fetchDataForCategory('rental'),
]);

return json({
sales: salesData,
rental: rentalData,
});
}
} catch (error) {
return json({ error: error.message }, { status: 500 });
Expand Down
4 changes: 2 additions & 2 deletions src/routes/api/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export async function fetchAdsForCategories(fetch, category) {
try {
const response = await fetch(`./api/?category=${category}`);
const response = await fetch(`api?category=${category}`);
if (!response.ok) {
throw new Error(`Network response was not ok for category: ${category}`);
throw new Error(`Network response was not ok.`);
}
return await response.json();
} catch (error) {
Expand Down

0 comments on commit 04f5564

Please sign in to comment.