mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-24 03:51:12 -05:00
feat: Implement entity creation functions
This commit is contained in:
66
src/lib/slugUtils.ts
Normal file
66
src/lib/slugUtils.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
|
||||
/**
|
||||
* Generate a URL-safe slug from a name
|
||||
*/
|
||||
export function generateSlugFromName(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure slug is unique by checking database and appending number if needed
|
||||
*/
|
||||
export async function ensureUniqueSlug(
|
||||
baseSlug: string,
|
||||
tableName: 'parks' | 'rides' | 'companies' | 'ride_models',
|
||||
excludeId?: string
|
||||
): Promise<string> {
|
||||
let slug = baseSlug;
|
||||
let counter = 1;
|
||||
|
||||
while (true) {
|
||||
// Check if slug exists
|
||||
let query = supabase
|
||||
.from(tableName)
|
||||
.select('id')
|
||||
.eq('slug', slug);
|
||||
|
||||
// Exclude current record when editing
|
||||
if (excludeId) {
|
||||
query = query.neq('id', excludeId);
|
||||
}
|
||||
|
||||
const { data, error } = await query.limit(1);
|
||||
|
||||
if (error) {
|
||||
console.error(`Error checking slug uniqueness in ${tableName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// If no match found, slug is unique
|
||||
if (!data || data.length === 0) {
|
||||
return slug;
|
||||
}
|
||||
|
||||
// Append counter and try again
|
||||
counter++;
|
||||
slug = `${baseSlug}-${counter}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and ensure unique slug in one operation
|
||||
*/
|
||||
export async function generateUniqueSlug(
|
||||
name: string,
|
||||
tableName: 'parks' | 'rides' | 'companies' | 'ride_models',
|
||||
excludeId?: string
|
||||
): Promise<string> {
|
||||
const baseSlug = generateSlugFromName(name);
|
||||
return ensureUniqueSlug(baseSlug, tableName, excludeId);
|
||||
}
|
||||
Reference in New Issue
Block a user