Skip to content

Commit

Permalink
Refactor MongoDB connection and update code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
loicBRAVO committed Feb 5, 2024
1 parent aaf9049 commit bfe25d8
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 26 deletions.
55 changes: 29 additions & 26 deletions back/src/index.ts
Original file line number Diff line number Diff line change
@@ -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);

Expand All @@ -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
Expand All @@ -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);
});
});

35 changes: 35 additions & 0 deletions back/src/routes/messageRoutes.ts
Original file line number Diff line number Diff line change
@@ -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;
27 changes: 27 additions & 0 deletions back/src/routes/usersRoutes.ts
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit bfe25d8

Please sign in to comment.