diff --git a/src/routes/api/channels/+server.ts b/src/routes/api/channels/+server.ts index 5a1491e..654ca4c 100644 --- a/src/routes/api/channels/+server.ts +++ b/src/routes/api/channels/+server.ts @@ -25,8 +25,6 @@ export async function GET({ url }) { }, }); - console.log(canaux); - canaux = canaux.map((canaux) => { return { ...canaux, @@ -36,7 +34,6 @@ export async function GET({ url }) { }); canaux = sortChannels(canaux); - console.log(canaux); return json(canaux); @@ -46,38 +43,46 @@ export async function GET({ url }) { } }else{ try { + + let channels = []; + const cachedChannels = await redisClient.get('channels'); if (cachedChannels != null) { logger.debug('Cache entry found, fetching channels from cache'); - return json(JSON.parse(cachedChannels)); + channels = JSON.parse(cachedChannels); + }else{ + logger.debug('No cache entry was found, fetching channels from database'); + } + if(channels.length < 10){ + logger.debug('Fetching channels from database to fill cache'); + let canaux = await prisma.channel.findMany({ + include: { + messages: { + take: 1, // Récupère le dernier message + orderBy: { createdAt: 'desc' }, // Trie par date décroissante + }, + }, + }); + + canaux = canaux.map((canaux) => { + return { + ...canaux, + lastMessage: canaux.messages.length > 0 ? canaux.messages[0] : null, + messages: undefined + }; + }); + + channels = channels.concat(canaux); + + channels = sortChannels(channels); + + channels = channels.slice(0, 10); + + await redisClient.set('channels', JSON.stringify(channels), { EX: 3600 }); } - logger.debug('No cache entry was found, fetching channels from database'); - let canaux = await prisma.channel.findMany({ - include: { - messages: { - take: 1, // Récupère le dernier message - orderBy: { createdAt: 'desc' }, // Trie par date décroissante - }, - }, - }); - - canaux = canaux.map((canaux) => { - return { - ...canaux, - lastMessage: canaux.messages.length > 0 ? canaux.messages[0] : null, - messages: undefined - }; - }); - - canaux = sortChannels(canaux); - console.log(canaux); - - logger.debug('Caching channels with EX of 3600 secs'); - await redisClient.set('channels', JSON.stringify(canaux), { EX: 3600 }); - - return json(canaux); + return json(channels); } catch (err) { logger.error(err) diff --git a/src/routes/api/channels/[id]/messages/+server.ts b/src/routes/api/channels/[id]/messages/+server.ts index 022a204..850429a 100644 --- a/src/routes/api/channels/[id]/messages/+server.ts +++ b/src/routes/api/channels/[id]/messages/+server.ts @@ -89,7 +89,7 @@ export async function POST({ params, request }) { try { // Créer un nouveau message dans MongoDB - const newMessage = await prisma.message.create({ + let newMessage = await prisma.message.create({ data: { userId, channelId, @@ -123,17 +123,35 @@ export async function POST({ params, request }) { //update the channels cache with the new message const cachedChannels = await redisClient.get('channels'); let channels = cachedChannels ? JSON.parse(cachedChannels) : []; - const channel = channels.find((c) => c.id === channelId); + let channel = channels.find((c) => c.id === channelId); if(channel){ - channel.lastMessage = newMessage; + channel.lastMessage = { + id: newMessage.id, + text: newMessage.text, + user: newMessage.user, + createdAt: newMessage.createdAt, + }; channel.lastUpdate = newMessage.createdAt; - channels = sortChannels(channels); - await redisClient.set('channels', JSON.stringify(channels), { EX: 600 }); - }else{ - channels = [newMessage.channel, ...channels]; - await redisClient.set('channels', JSON.stringify(channels), { EX: 600 }); - } + channel.messages = undefined; + }else{ + channel = {...newMessage.channel, lastMessage: { + id: newMessage.id, + text: newMessage.text, + user: newMessage.user, + createdAt: newMessage.createdAt, + }, lastUpdate: newMessage.createdAt, messages: undefined}; + } + channels = [channel, ...channels]; + await redisClient.set('channels', JSON.stringify(channels), { EX: 600 }); + + newMessage.channel = { + id: newMessage.channel.id, + name: newMessage.channel.name, + lastMessage: channel.lastMessage, + lastUpdate: channel.lastUpdate, + messages: undefined + }; logger.debug(`Nouveau message ajouté pour le channel : ${channelId}`); return json(newMessage, { status: 201 }); diff --git a/src/routes/chats/+page.svelte b/src/routes/chats/+page.svelte index 5df12c4..84f78f4 100644 --- a/src/routes/chats/+page.svelte +++ b/src/routes/chats/+page.svelte @@ -19,11 +19,18 @@ }); socket.on("new-message", (message) => { - const channel = channels.find((channel) => channel.id === message.channel.id); - if (channel) { - channel.lastMessage = message; - channel.lastUpdate = message.createdAt; + const channel = message.channel + if(channels.find(c => c.id === channel.id)) { + channels = channels.map((c) => { + if (c.id === channel.id) { + c.lastMessage = message; + c.lastUpdate = message.createdAt; + } + return c; + }); channels = [channel, ...channels.filter((c) => c.id !== channel.id)]; + }else{ + channels = [channel, ...channels]; } }); diff --git a/src/routes/chats/[id]/+page.svelte b/src/routes/chats/[id]/+page.svelte index 4256d7c..2218674 100644 --- a/src/routes/chats/[id]/+page.svelte +++ b/src/routes/chats/[id]/+page.svelte @@ -50,18 +50,21 @@ } } - let currentPage = 1; let isLoading = false; + const limit = 10; async function loadMoreMessages() { - if (isLoading) { return; } isLoading = true; try { - const response = await fetch(`/api/channels/${data.channelId}/messages?page=${currentPage + 1}&limit=10`, { + // Calculer la page à charger en fonction du nombre total de messages existants + const totalMessages = messages.length; + const pageToLoad = Math.floor(totalMessages / limit) + 1; + + const response = await fetch(`/api/channels/${data.channelId}/messages?page=${pageToLoad}&limit=${limit}`, { method: 'GET', headers: { 'Content-Type': 'application/json', @@ -70,22 +73,31 @@ if (response.ok) { const newMessages = await response.json(); - if(newMessages.messages.length <= 0){ - console.log('Pas d\'autres anciens messages'); + + if (newMessages.messages.length <= 0) { + console.log("Pas d'autres anciens messages"); return; } - messages = [...newMessages.messages, ...messages]; // Ajouter les nouveaux messages en haut - currentPage++; + + // Éviter les doublons en filtrant les messages déjà présents + const existingMessageIds = new Set(messages.map((msg) => msg.id)); + const filteredMessages = newMessages.messages.filter( + (msg) => !existingMessageIds.has(msg.id) + ); + + if (filteredMessages.length > 0) { + messages = [...filteredMessages, ...messages]; // Ajouter les nouveaux messages en haut + console.log(`${filteredMessages.length} nouveaux messages ajoutés`); + } else { + console.log("Aucun nouveau message à ajouter (tous déjà chargés)"); + } } else { - console.error('Erreur lors du chargement des anciens messages'); + console.error("Erreur lors du chargement des anciens messages"); } } catch (error) { - console.error('Erreur réseau lors du chargement des messages:', error); + console.error("Erreur réseau lors du chargement des messages:", error); } finally { isLoading = false; - - - } } @@ -97,7 +109,7 @@ const position = container.scrollHeight - container.scrollTop - container.clientHeight; isAtBottom = position <= threshold; - if(container.scrollTop <= threshold){ + if(container.scrollTop <= 0){ loadMoreMessages(); } } @@ -129,12 +141,15 @@ } } - + let isFirstLoad = 0; onMount(async () => { if (scrollContainer) { const observer = new MutationObserver(async () => { - await scrollToBottom(); + if (isFirstLoad <= messages.length) { + await scrollToBottom(); // Appel à scrollToBottom() seulement lors du premier chargement + isFirstLoad++; // Une fois les messages chargés pour la première fois, on empêche les appels suivants + } if(scrollContainer.scrollTop <= 5){ const newHeight = scrollContainer.scrollHeight; if (newHeight !== previousHeight) {