Files
scan-wave/src/routes/private/events/queries.ts
2025-07-12 22:01:05 +02:00

71 lines
2.4 KiB
TypeScript

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;
// 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');
}
}