Spaces:
Running
Running
import { supabase } from "@/integrations/supabase/client"; | |
import { Database } from "@/integrations/supabase/types"; | |
import { ContentItem, Category } from "@/lib/types"; | |
// Type for Urdf table row | |
type UrdfRow = Database["public"]["Tables"]["urdf"]["Row"]; | |
// Convert a Supabase URDF row to our ContentItem format | |
export const mapUrdfToContentItem = (urdf: UrdfRow): ContentItem => { | |
// Convert tags to categories | |
const categories = urdf.tags || []; | |
return { | |
id: urdf.id, | |
title: urdf.name, | |
imageUrl: urdf.image_uri || "/placeholder.svg", // This now contains the storage path or full URL | |
description: urdf.summary || undefined, | |
categories, | |
urdfPath: urdf.urdf_uri || "", | |
}; | |
}; | |
// Get all URDFs | |
export const getUrdfs = async (): Promise<ContentItem[]> => { | |
console.log("Fetching URDFs"); | |
const { data, error } = await supabase.from("urdf").select("*").order("name"); | |
console.log("URDFs fetched", data); | |
if (error) { | |
console.error("Error fetching URDFs:", error); | |
throw error; | |
} | |
return (data || []).map(mapUrdfToContentItem); | |
}; | |
// Get unique categories from all URDFs | |
export const getCategories = async (): Promise<Category[]> => { | |
const { data, error } = await supabase.from("urdf").select("tags"); | |
if (error) { | |
console.error("Error fetching categories:", error); | |
throw error; | |
} | |
// Extract all unique tags across all URDFs | |
const allTags = new Set<string>(); | |
data.forEach((urdf) => { | |
if (urdf.tags && Array.isArray(urdf.tags)) { | |
urdf.tags.forEach((tag) => allTags.add(tag)); | |
} | |
}); | |
// Convert to Category objects | |
return Array.from(allTags).map((tag) => ({ | |
id: tag, | |
name: tag.charAt(0).toUpperCase() + tag.slice(1), // Capitalize first letter | |
})); | |
}; | |
// Get URDF by ID | |
export const getUrdfById = async (id: string): Promise<ContentItem | null> => { | |
const { data, error } = await supabase | |
.from("urdf") | |
.select("*") | |
.eq("id", id) | |
.single(); | |
if (error) { | |
if (error.code === "PGRST116") { | |
// Row not found | |
return null; | |
} | |
console.error("Error fetching URDF by ID:", error); | |
throw error; | |
} | |
return mapUrdfToContentItem(data); | |
}; | |
// Get public URL for image | |
export const getImageUrl = async (path: string): Promise<string> => { | |
if (!path || path.startsWith('http') || path.startsWith('data:')) { | |
return path || '/placeholder.svg'; | |
} | |
try { | |
// Get public URL for the image | |
const { data, error } = await supabase.storage | |
.from('urdf-images') | |
.createSignedUrl(path, 3600); // 1 hour expiry | |
if (data && !error) { | |
return data.signedUrl; | |
} | |
} catch (error) { | |
console.error(`Error fetching image at ${path}:`, error); | |
} | |
return '/placeholder.svg'; | |
}; | |