diff --git a/src/lib/components/ui/CreateChat.svelte b/src/lib/components/ui/CreateChat.svelte index c1e6dd8..51d3f93 100644 --- a/src/lib/components/ui/CreateChat.svelte +++ b/src/lib/components/ui/CreateChat.svelte @@ -1,5 +1,4 @@ {#if show} @@ -21,6 +39,7 @@

{user.prenom} {user.nom}

{user.description}

+ {/if} diff --git a/src/lib/stores/socket.ts b/src/lib/stores/socket.ts new file mode 100644 index 0000000..ac1fa92 --- /dev/null +++ b/src/lib/stores/socket.ts @@ -0,0 +1,17 @@ +import { io } from "socket.io-client"; + +// Initialisation de la socket +export const initSocket = () => { + const socketInstance = io("http://localhost:5173"); + + // Événements globaux de connexion + socketInstance.on("connect", () => { + console.log("Connected to Socket.IO server:", socketInstance.id); + }); + + socketInstance.on("disconnect", () => { + console.log("Disconnected from Socket.IO server"); + }); + + return socketInstance; +} \ No newline at end of file diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 3ce69be..36e1be9 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,6 +1,9 @@ import { redirect } from '@sveltejs/kit'; +import { initSocket } from "$lib/stores/socket"; + export async function load({ locals, url }) { + const token = locals.token; if (token == undefined && url.pathname !== "/") { diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index 153ebff..d0563d9 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -1,5 +1,5 @@ import { type Actions } from '@sveltejs/kit'; -import { redirect, error } from '@sveltejs/kit'; +import { redirect, error, fail } from '@sveltejs/kit'; import logger from '$lib/logger'; export async function load({locals}) { @@ -9,7 +9,7 @@ export async function load({locals}) { } export const actions: Actions = { - login: async ({request, fetch, cookies, locals}) => { + login: async ({request, fetch, cookies}) => { const formData = await request.formData(); const response = await fetch('/api/auth/login', { @@ -38,8 +38,7 @@ export const actions: Actions = { return redirect(302, "/chats"); } else { - - return error(400, data.message); + return fail(400, { error: data.message }); } }, @@ -65,8 +64,7 @@ export const actions: Actions = { return redirect(302, "/chats"); } else { - - return error(400, data.message); + return fail(400, { error: data.message }); } } } \ No newline at end of file diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 1c48e5d..ef5b570 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,10 +1,27 @@ @@ -69,4 +86,6 @@ - \ No newline at end of file + + + ($showAlert = false)} /> \ No newline at end of file diff --git a/src/routes/api/auth/login/+server.ts b/src/routes/api/auth/login/+server.ts index 24f9211..69324d1 100644 --- a/src/routes/api/auth/login/+server.ts +++ b/src/routes/api/auth/login/+server.ts @@ -26,7 +26,7 @@ export async function POST({request}) { logger.debug(`Found user with email (${email}) in database`); try { if (await argon2.verify(user.password, password)) { - + logger.debug(`Password for user ${user.email} is correct.`); // @ts-ignore const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: "1h" }); logger.debug(`Generated a JWT token for user ${user.email}.`) @@ -39,7 +39,7 @@ export async function POST({request}) { // eslint-disable-next-line @typescript-eslint/no-unused-vars } catch (e) { logger.error(e); - return error(500, {message: "Erreur interne."}); + return error(500, {message: e.body.message}); } diff --git a/src/routes/api/channels/+server.ts b/src/routes/api/channels/+server.ts index a38ed3d..ec06b75 100644 --- a/src/routes/api/channels/+server.ts +++ b/src/routes/api/channels/+server.ts @@ -18,12 +18,24 @@ export async function GET({ params, url }) { include: { messages: { take: 1, // Récupère le dernier message - orderBy: { createdAt: 'desc' }, // Trie par date décroissante + orderBy: { createdAt: 'desc' },// Trie par date décroissante + // as lastMessage not list last message }, }, }); + console.log(canaux); + + canaux = canaux.map((canaux) => { + return { + ...canaux, + lastMessage: canaux.messages.length > 0 ? canaux.messages[0] : null, + messages: undefined + }; + }); + canaux = sortChannels(canaux); + console.log(canaux); return json(canaux); @@ -50,7 +62,16 @@ export async function GET({ params, url }) { }, }); + 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 }); @@ -69,7 +90,7 @@ export async function POST({ request }) { const { name } = await request.json(); try { - const canal = await prisma.channel.create({ + let canal = await prisma.channel.create({ data: { name }, @@ -79,13 +100,16 @@ export async function POST({ request }) { const cachedChanels = await redisClient.get('channels'); let channels = cachedChanels != null ? JSON.parse(cachedChanels) : []; - console.log(channels); - console.log(canal); + + canal = { + ...canal, + lastMessage: null, + messages: undefined + } channels.push(canal); channels = sortChannels(channels); - console.log(channels); logger.debug(`Added channel (${canal.id}) to channels cache.`); await redisClient.set('channels', JSON.stringify(channels), { EX: 600 }); @@ -100,11 +124,16 @@ export async function POST({ request }) { } function sortChannels(channels) { - return channels.sort((a, b) => { - // Vérifie si 'a.messages' existe et est un tableau, sinon utilise la date de création du canal - const lastMessageA = Array.isArray(a.messages) && a.messages.length > 0 ? a.messages[0]?.createdAt : a.createdAt; - const lastMessageB = Array.isArray(b.messages) && b.messages.length > 0 ? b.messages[0]?.createdAt : b.createdAt; + channels = channels.map((channel) => { + return { + ...channel, + lastUpdate : channel.lastMessage != null ? channel.lastMessage.createdAt : channel.createdAt + }; + }); - return new Date(lastMessageB).getTime() - new Date(lastMessageA).getTime(); + return channels.sort((a, b) => { + return new Date(b.lastUpdate) - new Date(a.lastUpdate); }); } + + diff --git a/src/routes/chats/+page.svelte b/src/routes/chats/+page.svelte index f0f031d..da9acd6 100644 --- a/src/routes/chats/+page.svelte +++ b/src/routes/chats/+page.svelte @@ -6,7 +6,7 @@ import ProfileCard from "$lib/components/ui/ProfileCard.svelte"; // Importer le composant ProfileCard import CreateChat from "$lib/components/ui/CreateChat.svelte"; // Importer le composant CreateChat import { formatDistanceToNow } from "$lib/utils/date.js"; - import { io } from 'socket.io-client'; + import { initSocket } from "$lib/stores/socket"; let showProfileCard = false; // État pour afficher ou masquer le ProfileCard let showCreateChat = false; // État pour afficher ou masquer CreateChat @@ -18,6 +18,12 @@ profilePictureUrl: 'path/to/profile-picture.jpg', // URL de l'image de profil }; + let socket = initSocket(); // Initialiser le socket + + socket.on("new-channel", (channel) => { + channels = [channel, ...channels]; + }); + function openProfileCard() { console.log('openProfileCard'); showProfileCard = true; // Inverser l'état pour afficher/masquer le ProfilCard @@ -85,12 +91,17 @@
{#each channels as channel} - + {/each}
- +