From bfe25d84b07e77156f652cf602ddfd374b586727 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20BRAVO?= <96313051+loicBRAVO@users.noreply.github.com> Date: Mon, 5 Feb 2024 11:39:29 +0100 Subject: [PATCH] Refactor MongoDB connection and update code formatting --- back/src/index.ts | 55 +++++++++++++++++--------------- back/src/routes/messageRoutes.ts | 35 ++++++++++++++++++++ back/src/routes/usersRoutes.ts | 27 ++++++++++++++++ 3 files changed, 91 insertions(+), 26 deletions(-) create mode 100644 back/src/routes/messageRoutes.ts create mode 100644 back/src/routes/usersRoutes.ts diff --git a/back/src/index.ts b/back/src/index.ts index a7bd2be..25c4227 100644 --- a/back/src/index.ts +++ b/back/src/index.ts @@ -1,26 +1,28 @@ -import express from 'express'; -import http from 'http'; -import { Server as SocketIOServer } from 'socket.io'; -import mongoose from 'mongoose'; -import Message from './models/Message'; -import dotenv from 'dotenv'; -import messageRouters from '../dist/routes/messageRoutes'; +import express from "express"; +import http from "http"; +import { Server as SocketIOServer } from "socket.io"; +import mongoose from "mongoose"; +import Message from "./models/Message"; +import dotenv from "dotenv"; +import messageRouters from "./routes/messageRoutes"; // Load environment variables from .env file dotenv.config(); - // Connect to MongoDB -mongoose.connect(`mongodb://${process.env.MONGODB_USER}:${process.env.MONGODB_USER_PASSWORD}@localhost:27017/${process.env.MONGO_INITDB_DATABASE}`) - .then(() => console.log('Connected to MongoDB')) - .catch((err: any) => console.error('Could not connect to MongoDB', err)); +mongoose + .connect( + `mongodb://${process.env.MONGODB_USER}:${process.env.MONGODB_USER_PASSWORD}@localhost:27017/${process.env.MONGO_INITDB_DATABASE}` + ) + .then(() => console.log("Connected to MongoDB")) + .catch((err: any) => console.error("Could not connect to MongoDB", err)); const app = express(); const server = http.createServer(app); const io = new SocketIOServer(server); // Configure Express to serve static files from the public folder -app.use(express.static('../front/public/')); +app.use(express.static("../front/public/")); app.use(express.json()); app.use(messageRouters); @@ -31,19 +33,21 @@ server.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); -io.on('connection', (socket) => { - console.log('User connected:', socket.id); +io.on("connection", (socket) => { + console.log("User connected:", socket.id); // Listen for incoming chat messages - socket.on('chat message', async (data) => { - console.log('Received message:', data); + socket.on("chat message", async (data) => { + console.log("Received message:", data); // Prepare the message document according to the updated schema const messageDocument = { - messages: [{ - timestamp: new Date(), - content: data.message, - }] + messages: [ + { + timestamp: new Date(), + content: data.message, + }, + ], }; // Instantiate the Message model with the document @@ -52,18 +56,17 @@ io.on('connection', (socket) => { try { // Save the message document to MongoDB await messageModel.save(); - console.log('Message saved to the database'); + console.log("Message saved to the database"); // Broadcast the message to all connected clients - io.emit('chat message', data); + io.emit("chat message", data); } catch (err) { - console.error('Error saving message to database:', err); + console.error("Error saving message to database:", err); } }); // Listen for user disconnection - socket.on('disconnect', () => { - console.log('User disconnected:', socket.id); + socket.on("disconnect", () => { + console.log("User disconnected:", socket.id); }); }); - diff --git a/back/src/routes/messageRoutes.ts b/back/src/routes/messageRoutes.ts new file mode 100644 index 0000000..ebf4dda --- /dev/null +++ b/back/src/routes/messageRoutes.ts @@ -0,0 +1,35 @@ +import express, { Request, Response } from "express"; +import MessageModel from "../models/Message"; + +const router = express.Router(); + +// Route pour récupérer tous les messages +router.get("/messages", async (req: Request, res: Response) => { + try { + const messages = await MessageModel.find({}); + res.json(messages); + } catch (error) { + res.status(500).json({ message: (error as Error).message }); + } +}); + +// Route pour ajouter un nouveau message +router.post("/messages", async (req: Request, res: Response) => { + const newMessage = { + timestamp: new Date(), // ou req.body.timestamp + content: req.body.content, + }; + + try { + const updatedDocument = await MessageModel.findOneAndUpdate( + {}, + { $push: { messages: newMessage } }, + { new: true, upsert: true } + ); + res.status(201).json(updatedDocument); + } catch (error) { + res.status(400).json({ message: (error as Error).message }); + } +}); + +export default router; diff --git a/back/src/routes/usersRoutes.ts b/back/src/routes/usersRoutes.ts new file mode 100644 index 0000000..c2ba644 --- /dev/null +++ b/back/src/routes/usersRoutes.ts @@ -0,0 +1,27 @@ +import express, { Request, Response } from "express"; +import UserModel from "../models/Users"; + +const router = express.Router(); + +// Route pour créer un nouvel utilisateur +router.post("/users", async (req: Request, res: Response) => { + const newUser = new UserModel({ + username: req.body.username, + password: req.body.password, // Vous devriez hasher le mot de passe + }); + + try { + const savedUser = await newUser.save(); + res.status(201).json(savedUser); + } catch (error) { + res.status(400).json({ message: (error as Error).message }); + } +}); + +// Route pour authentifier un utilisateur +// Ajoutez ici la logique d'authentification +router.post("/users/authenticate", async (req: Request, res: Response) => { + // Implémentation de l'authentification +}); + +export default router;