add sockets and change subscription

This commit is contained in:
DenAntonov
2025-06-12 21:04:12 +03:00
parent bffa3fa2a3
commit 24ff712306
6 changed files with 199 additions and 83 deletions

View File

@@ -1,64 +1,59 @@
const router = require('express').Router();
const { getSupabaseClient } = require('./supabaseClient');
const { getIo } = require('../../../io'); // Импортируем Socket.IO
// Получить все сообщения в чате с информацией о пользователе
router.get('/messages', async (req, res) => {
console.log('📬 [Server] GET /messages запрос получен');
console.log('📬 [Server] Query параметры:', req.query);
const supabase = getSupabaseClient();
const { chat_id, limit = 50, offset = 0 } = req.query;
if (!chat_id) {
console.log('❌ [Server] Ошибка: chat_id обязателен');
return res.status(400).json({ error: 'chat_id required' });
}
try {
console.log('🔍 [Server] Выполняем запрос к Supabase для чата:', chat_id);
// Получаем сообщения
const { data: messages, error } = await supabase
.from('messages')
.select('*')
.eq('chat_id', chat_id)
.order('created_at', { ascending: false })
.limit(limit)
.range(offset, offset + limit - 1);
if (error) {
console.log('❌ [Server] Ошибка получения сообщений:', error);
return res.status(400).json({ error: error.message });
const { chat_id, limit = 50, offset = 0 } = req.query;
if (!chat_id) {
return res.status(400).json({ error: 'chat_id is required' });
}
const supabase = getSupabaseClient();
// Получаем профили пользователей для всех уникальных user_id
let data = messages || [];
if (data.length > 0) {
const userIds = [...new Set(data.map(msg => msg.user_id))];
console.log('👥 [Server] Получаем профили для пользователей:', userIds);
const { data, error } = await supabase
.from('messages')
.select(`
*,
user_profiles (
id,
full_name,
avatar_url
)
`)
.eq('chat_id', chat_id)
.order('created_at', { ascending: true })
.range(offset, offset + limit - 1);
if (error) {
return res.status(500).json({ error: 'Failed to fetch messages' });
}
// Получаем уникальные ID пользователей из сообщений, у которых нет профиля
const messagesWithoutProfiles = data.filter(msg => !msg.user_profiles);
const userIds = [...new Set(messagesWithoutProfiles.map(msg => msg.user_id))];
if (userIds.length > 0) {
const { data: profiles, error: profilesError } = await supabase
.from('user_profiles')
.select('id, full_name, avatar_url')
.in('id', userIds);
if (!profilesError && profiles) {
// Объединяем сообщения с профилями
data = data.map(msg => ({
...msg,
user_profiles: profiles.find(profile => profile.id === msg.user_id) || null
}));
console.log('✅ [Server] Профили пользователей добавлены к сообщениям');
} else {
console.log('⚠️ [Server] Ошибка получения профилей пользователей:', profilesError);
// Добавляем профили к сообщениям
data.forEach(message => {
if (!message.user_profiles) {
message.user_profiles = profiles.find(profile => profile.id === message.user_id) || null;
}
});
}
}
console.log('✅ [Server] Сообщения получены:', data?.length || 0, 'шт.');
res.json(data?.reverse() || []); // Возвращаем в хронологическом порядке
}
res.json(data);
} catch (err) {
console.log('❌ [Server] Неожиданная ошибка:', err);
res.status(500).json({ error: 'Internal server error' });
res.status(500).json({ error: 'Unexpected error occurred' });
}
});
@@ -94,6 +89,9 @@ router.post('/messages', async (req, res) => {
...newMessage,
user_profiles: userProfile || null
};
// Отправка через Socket.IO теперь происходит автоматически через Supabase Real-time подписку
// Это предотвращает дублирование сообщений
res.json(data);
});