commiting working frontend with no backend except auth with supabase

This commit is contained in:
Harivansh Rathi 2024-12-07 16:54:00 -05:00
parent 1eb339623c
commit 8cfff27165
2 changed files with 85 additions and 84 deletions

2
.env Normal file
View file

@ -0,0 +1,2 @@
VITE_SUPABASE_URL=https://nvatjthzedykhikmttot.supabase.co
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im52YXRqdGh6ZWR5a2hpa210dG90Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzM1OTYxOTMsImV4cCI6MjA0OTE3MjE5M30.u4euR8U-XxxvOdLFmWJD2yrd4E_MPMt_X1yqRrDTF2I

View file

@ -1,83 +1,89 @@
import { supabase } from './supabase';
import type { ChatInstance, ChatMessage } from '../types/supabase'; import type { ChatInstance, ChatMessage } from '../types/supabase';
// Helper function to generate UUIDs
const generateId = () => crypto.randomUUID();
// Helper functions for localStorage
const getFromStorage = <T>(key: string): T[] => {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : [];
};
const setInStorage = <T>(key: string, data: T[]) => {
localStorage.setItem(key, JSON.stringify(data));
};
export const chatService = { export const chatService = {
async createChatInstance(userId: string, title: string): Promise<ChatInstance | null> { async createChatInstance(userId: string, title: string): Promise<ChatInstance | null> {
const { data, error } = await supabase try {
.from('chat_instances') const chatInstance: ChatInstance = {
.insert({ id: generateId(),
created_at: new Date().toISOString(),
user_id: userId, user_id: userId,
title, title,
last_message_at: new Date().toISOString(), last_message_at: new Date().toISOString(),
}) };
.select()
.single();
if (error) { const chats = getFromStorage<ChatInstance>('chat_instances');
chats.push(chatInstance);
setInStorage('chat_instances', chats);
return chatInstance;
} catch (error) {
console.error('Error creating chat instance:', error); console.error('Error creating chat instance:', error);
return null; return null;
} }
return data;
}, },
async getChatInstance(chatId: string): Promise<ChatInstance | null> { async getChatInstance(chatId: string): Promise<ChatInstance | null> {
const { data, error } = await supabase try {
.from('chat_instances') const chats = getFromStorage<ChatInstance>('chat_instances');
.select() return chats.find(chat => chat.id === chatId) || null;
.eq('id', chatId) } catch (error) {
.single();
if (error) {
console.error('Error fetching chat instance:', error); console.error('Error fetching chat instance:', error);
return null; return null;
} }
return data;
}, },
async updateChatTitle(chatId: string, title: string): Promise<boolean> { async updateChatTitle(chatId: string, title: string): Promise<boolean> {
const { error } = await supabase try {
.from('chat_instances') const chats = getFromStorage<ChatInstance>('chat_instances');
.update({ title }) const chatIndex = chats.findIndex(chat => chat.id === chatId);
.eq('id', chatId);
if (error) { if (chatIndex === -1) return false;
chats[chatIndex].title = title;
setInStorage('chat_instances', chats);
return true;
} catch (error) {
console.error('Error updating chat title:', error); console.error('Error updating chat title:', error);
return false; return false;
} }
return true;
}, },
async getChatInstances(userId: string): Promise<ChatInstance[]> { async getChatInstances(userId: string): Promise<ChatInstance[]> {
const { data, error } = await supabase try {
.from('chat_instances') const chats = getFromStorage<ChatInstance>('chat_instances');
.select() return chats
.eq('user_id', userId) .filter(chat => chat.user_id === userId)
.order('last_message_at', { ascending: false }); .sort((a, b) => new Date(b.last_message_at).getTime() - new Date(a.last_message_at).getTime());
} catch (error) {
if (error) {
console.error('Error fetching chat instances:', error); console.error('Error fetching chat instances:', error);
return []; return [];
} }
return data;
}, },
async getChatMessages(chatId: string): Promise<ChatMessage[]> { async getChatMessages(chatId: string): Promise<ChatMessage[]> {
const { data, error } = await supabase try {
.from('chat_messages') const messages = getFromStorage<ChatMessage>('chat_messages');
.select() return messages
.eq('chat_id', chatId) .filter(message => message.chat_id === chatId)
.order('created_at', { ascending: true }); .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
} catch (error) {
if (error) {
console.error('Error fetching chat messages:', error); console.error('Error fetching chat messages:', error);
return []; return [];
} }
return data;
}, },
async addMessage( async addMessage(
@ -86,58 +92,51 @@ export const chatService = {
role: 'user' | 'assistant', role: 'user' | 'assistant',
metadata?: ChatMessage['metadata'] metadata?: ChatMessage['metadata']
): Promise<ChatMessage | null> { ): Promise<ChatMessage | null> {
const { data: message, error: messageError } = await supabase try {
.from('chat_messages') const message: ChatMessage = {
.insert({ id: generateId(),
chat_id: chatId, chat_id: chatId,
content, content,
role, role,
created_at: new Date().toISOString(),
metadata, metadata,
}) };
.select()
.single();
if (messageError) { const messages = getFromStorage<ChatMessage>('chat_messages');
console.error('Error adding message:', messageError); messages.push(message);
setInStorage('chat_messages', messages);
// Update last_message_at in chat instance
const chats = getFromStorage<ChatInstance>('chat_instances');
const chatIndex = chats.findIndex(chat => chat.id === chatId);
if (chatIndex !== -1) {
chats[chatIndex].last_message_at = new Date().toISOString();
setInStorage('chat_instances', chats);
}
return message;
} catch (error) {
console.error('Error adding message:', error);
return null; return null;
} }
// Update last_message_at in chat instance
const { error: updateError } = await supabase
.from('chat_instances')
.update({ last_message_at: new Date().toISOString() })
.eq('id', chatId);
if (updateError) {
console.error('Error updating chat instance:', updateError);
}
return message;
}, },
async deleteChatInstance(chatId: string): Promise<boolean> { async deleteChatInstance(chatId: string): Promise<boolean> {
// Delete all messages first try {
const { error: messagesError } = await supabase // Delete all messages for this chat
.from('chat_messages') const messages = getFromStorage<ChatMessage>('chat_messages');
.delete() const filteredMessages = messages.filter(message => message.chat_id !== chatId);
.eq('chat_id', chatId); setInStorage('chat_messages', filteredMessages);
if (messagesError) { // Delete the chat instance
console.error('Error deleting chat messages:', messagesError); const chats = getFromStorage<ChatInstance>('chat_instances');
const filteredChats = chats.filter(chat => chat.id !== chatId);
setInStorage('chat_instances', filteredChats);
return true;
} catch (error) {
console.error('Error deleting chat instance:', error);
return false; return false;
} }
// Then delete the chat instance
const { error: instanceError } = await supabase
.from('chat_instances')
.delete()
.eq('id', chatId);
if (instanceError) {
console.error('Error deleting chat instance:', instanceError);
return false;
}
return true;
}, },
}; };