Fix existing room error handling with AppError

This commit is contained in:
NouhailaAater 2025-02-28 02:28:47 -05:00
parent 4cc6ee79e4
commit 2fc922d01f
2 changed files with 30 additions and 22 deletions

View file

@ -29,13 +29,12 @@ class RoomsController {
const roomExists = await this.rooms.roomExists(normalizedTitle);
if (roomExists) {
const error = new AppError(ROOM_ALREADY_EXISTS);
error.message = "Cette salle existe déjà";
const error = new Error("Room already exists");
error.statusCode = 409;
throw error;
}
const result = await this.rooms.create(normalizedTitle, req.user.userId);
return res.status(201).json({
@ -43,10 +42,17 @@ class RoomsController {
roomId: result.insertedId,
});
} catch (error) {
next(Object.assign(error, { message: error.message }));
if (error instanceof Error) {
if (error.message === "Room already exists") {
return next(new AppError(ROOM_ALREADY_EXISTS));
}
}
next(error);
}
};
getUserRooms = async (req, res, next) => {
try {
const rooms = await this.rooms.getUserRooms(req.user.userId);
@ -200,7 +206,9 @@ class RoomsController {
if (!title) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const exists = await this.rooms.roomExists(title);
const userId = req.user.userId;
const exists = await this.rooms.roomExists(title, userId);
return res.status(200).json({
exists: exists,

View file

@ -7,21 +7,21 @@ class Rooms
this.db = db;
}
async create(title, userId)
{
async create(title, userId) {
if (!title || !userId) {
throw new Error('Missing required parameter(s)', 400);
throw new Error('Missing required parameter(s)');
}
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection('rooms');
const normalizedTitle = title.toLowerCase();
const normalizedTitle = title.toUpperCase();
const existingRoom = await roomsCollection.findOne({ title: normalizedTitle, userId: userId });
const existingRoom = await roomsCollection.findOne({ title: normalizedTitle });
if (existingRoom) {
throw new Error('Room already exists', 409);
// Lancer une erreur générique ici
throw new Error('Room already exists');
}
const newRoom = {
@ -33,7 +33,6 @@ class Rooms
const result = await roomsCollection.insertOne(newRoom);
return result.insertedId;
}
@ -119,14 +118,15 @@ class Rooms
return true;
}
async roomExists(title)
{ // Ajouter userId en paramètre
async roomExists(title, userId)
{
try
{
await this.db.connect();
const conn = this.db.getConnection();
const existingRoom = await conn.collection('rooms').findOne({
title: title.toLowerCase()
title: title.toUpperCase(),
userId: userId
});
return existingRoom ? true : false;
} catch (error)