Regles de certains bug et de cache des messages et des channels
This commit is contained in:
parent
19e66750ad
commit
5e1630af28
4 changed files with 102 additions and 57 deletions
|
@ -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,14 +43,19 @@ 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: {
|
||||
|
@ -71,13 +73,16 @@ export async function GET({ url }) {
|
|||
};
|
||||
});
|
||||
|
||||
canaux = sortChannels(canaux);
|
||||
console.log(canaux);
|
||||
channels = channels.concat(canaux);
|
||||
|
||||
logger.debug('Caching channels with EX of 3600 secs');
|
||||
await redisClient.set('channels', JSON.stringify(canaux), { EX: 3600 });
|
||||
channels = sortChannels(channels);
|
||||
|
||||
return json(canaux);
|
||||
channels = channels.slice(0, 10);
|
||||
|
||||
await redisClient.set('channels', JSON.stringify(channels), { EX: 3600 });
|
||||
}
|
||||
|
||||
return json(channels);
|
||||
|
||||
} catch (err) {
|
||||
logger.error(err)
|
||||
|
|
|
@ -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 });
|
||||
|
|
|
@ -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];
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
@ -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');
|
||||
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.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) {
|
||||
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) {
|
||||
|
|
Loading…
Add table
Reference in a new issue