Regles de certains bug et de cache des messages et des channels

This commit is contained in:
Bilal Dieumegard 2024-12-15 22:09:52 +01:00
parent 19e66750ad
commit 5e1630af28
4 changed files with 102 additions and 57 deletions

View file

@ -25,8 +25,6 @@ export async function GET({ url }) {
}, },
}); });
console.log(canaux);
canaux = canaux.map((canaux) => { canaux = canaux.map((canaux) => {
return { return {
...canaux, ...canaux,
@ -36,7 +34,6 @@ export async function GET({ url }) {
}); });
canaux = sortChannels(canaux); canaux = sortChannels(canaux);
console.log(canaux);
return json(canaux); return json(canaux);
@ -46,14 +43,19 @@ export async function GET({ url }) {
} }
}else{ }else{
try { try {
let channels = [];
const cachedChannels = await redisClient.get('channels'); const cachedChannels = await redisClient.get('channels');
if (cachedChannels != null) { if (cachedChannels != null) {
logger.debug('Cache entry found, fetching channels from cache'); 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'); 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({ let canaux = await prisma.channel.findMany({
include: { include: {
messages: { messages: {
@ -71,13 +73,16 @@ export async function GET({ url }) {
}; };
}); });
canaux = sortChannels(canaux); channels = channels.concat(canaux);
console.log(canaux);
logger.debug('Caching channels with EX of 3600 secs'); channels = sortChannels(channels);
await redisClient.set('channels', JSON.stringify(canaux), { EX: 3600 });
return json(canaux); channels = channels.slice(0, 10);
await redisClient.set('channels', JSON.stringify(channels), { EX: 3600 });
}
return json(channels);
} catch (err) { } catch (err) {
logger.error(err) logger.error(err)

View file

@ -89,7 +89,7 @@ export async function POST({ params, request }) {
try { try {
// Créer un nouveau message dans MongoDB // Créer un nouveau message dans MongoDB
const newMessage = await prisma.message.create({ let newMessage = await prisma.message.create({
data: { data: {
userId, userId,
channelId, channelId,
@ -123,17 +123,35 @@ export async function POST({ params, request }) {
//update the channels cache with the new message //update the channels cache with the new message
const cachedChannels = await redisClient.get('channels'); const cachedChannels = await redisClient.get('channels');
let channels = cachedChannels ? JSON.parse(cachedChannels) : []; let channels = cachedChannels ? JSON.parse(cachedChannels) : [];
const channel = channels.find((c) => c.id === channelId); let channel = channels.find((c) => c.id === channelId);
if(channel){ if(channel){
channel.lastMessage = newMessage; channel.lastMessage = {
id: newMessage.id,
text: newMessage.text,
user: newMessage.user,
createdAt: newMessage.createdAt,
};
channel.lastUpdate = newMessage.createdAt; channel.lastUpdate = newMessage.createdAt;
channels = sortChannels(channels); channel.messages = undefined;
await redisClient.set('channels', JSON.stringify(channels), { EX: 600 });
}else{
channels = [newMessage.channel, ...channels];
await redisClient.set('channels', JSON.stringify(channels), { EX: 600 });
}
}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}`); logger.debug(`Nouveau message ajouté pour le channel : ${channelId}`);
return json(newMessage, { status: 201 }); return json(newMessage, { status: 201 });

View file

@ -19,11 +19,18 @@
}); });
socket.on("new-message", (message) => { socket.on("new-message", (message) => {
const channel = channels.find((channel) => channel.id === message.channel.id); const channel = message.channel
if (channel) { if(channels.find(c => c.id === channel.id)) {
channel.lastMessage = message; channels = channels.map((c) => {
channel.lastUpdate = message.createdAt; if (c.id === channel.id) {
c.lastMessage = message;
c.lastUpdate = message.createdAt;
}
return c;
});
channels = [channel, ...channels.filter((c) => c.id !== channel.id)]; channels = [channel, ...channels.filter((c) => c.id !== channel.id)];
}else{
channels = [channel, ...channels];
} }
}); });

View file

@ -50,18 +50,21 @@
} }
} }
let currentPage = 1;
let isLoading = false; let isLoading = false;
const limit = 10;
async function loadMoreMessages() { async function loadMoreMessages() {
if (isLoading) { if (isLoading) {
return; return;
} }
isLoading = true; isLoading = true;
try { 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', method: 'GET',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -70,22 +73,31 @@
if (response.ok) { if (response.ok) {
const newMessages = await response.json(); const newMessages = await response.json();
if (newMessages.messages.length <= 0) { if (newMessages.messages.length <= 0) {
console.log('Pas d\'autres anciens messages'); console.log("Pas d'autres anciens messages");
return; 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 { } else {
console.error('Erreur lors du chargement des anciens messages'); console.log("Aucun nouveau message à ajouter (tous déjà chargés)");
}
} else {
console.error("Erreur lors du chargement des anciens messages");
} }
} catch (error) { } 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 { } finally {
isLoading = false; isLoading = false;
} }
} }
@ -97,7 +109,7 @@
const position = container.scrollHeight - container.scrollTop - container.clientHeight; const position = container.scrollHeight - container.scrollTop - container.clientHeight;
isAtBottom = position <= threshold; isAtBottom = position <= threshold;
if(container.scrollTop <= threshold){ if(container.scrollTop <= 0){
loadMoreMessages(); loadMoreMessages();
} }
} }
@ -129,12 +141,15 @@
} }
} }
let isFirstLoad = 0;
onMount(async () => { onMount(async () => {
if (scrollContainer) { if (scrollContainer) {
const observer = new MutationObserver(async () => { 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){ if(scrollContainer.scrollTop <= 5){
const newHeight = scrollContainer.scrollHeight; const newHeight = scrollContainer.scrollHeight;
if (newHeight !== previousHeight) { if (newHeight !== previousHeight) {