Use tanstack for caching of events
This commit is contained in:
73
src/routes/private/events/queries.ts
Normal file
73
src/routes/private/events/queries.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js';
|
||||
|
||||
export interface Event {
|
||||
id: string;
|
||||
name: string;
|
||||
date: string;
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified function to get events or search events based on a search term
|
||||
* @param supabase The Supabase client
|
||||
* @param searchTerm Optional search term - if provided, will filter by name
|
||||
* @returns Combined array of regular and archived events
|
||||
*/
|
||||
export async function getEvents(supabase: SupabaseClient, searchTerm: string = '') {
|
||||
try {
|
||||
const searchPattern = searchTerm.trim() ? `%${searchTerm}%` : null;
|
||||
|
||||
console.log('Actually fetching!');
|
||||
|
||||
// Build regular events query
|
||||
let regularQuery = supabase
|
||||
.from('events')
|
||||
.select('id, name, date')
|
||||
.order('date', { ascending: false });
|
||||
|
||||
// Apply search filter if needed
|
||||
if (searchPattern) {
|
||||
regularQuery = regularQuery.ilike('name', searchPattern);
|
||||
}
|
||||
|
||||
// Fetch regular events
|
||||
const { data: regularEvents, error: regularError } = await regularQuery;
|
||||
|
||||
if (regularError) throw regularError;
|
||||
|
||||
// Build archived events query
|
||||
let archivedQuery = supabase
|
||||
.from('events_archived')
|
||||
.select('id, name, date')
|
||||
.order('date', { ascending: false })
|
||||
.limit(searchPattern ? 50 : 20); // Fetch more when searching
|
||||
|
||||
// Apply search filter if needed
|
||||
if (searchPattern) {
|
||||
archivedQuery = archivedQuery.ilike('name', searchPattern);
|
||||
}
|
||||
|
||||
// Fetch archived events
|
||||
const { data: archivedEvents, error: archivedError } = await archivedQuery;
|
||||
|
||||
if (archivedError) throw archivedError;
|
||||
|
||||
// Merge both arrays, marking archived events
|
||||
const regularMapped = (regularEvents || []).map((event) => ({ ...event, archived: false }));
|
||||
const archivedMapped = (archivedEvents || []).map((event) => ({
|
||||
...event,
|
||||
archived: true
|
||||
}));
|
||||
|
||||
// Sort all events by date (newest first)
|
||||
const combined = [...regularMapped, ...archivedMapped];
|
||||
combined.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
|
||||
|
||||
return combined;
|
||||
} catch (error) {
|
||||
console.error('Error fetching events:', error);
|
||||
throw new Error(searchTerm.trim()
|
||||
? `Failed to search events for "${searchTerm}"`
|
||||
: 'Failed to load events');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user