AppErreur lancée par les contrôleurs, Erreur lancée par les modèles.

This commit is contained in:
C. Fuhrman 2025-02-27 09:06:58 -05:00
parent 3855eca6c6
commit 0d56fa246d
2 changed files with 161 additions and 156 deletions

View file

@ -1,5 +1,3 @@
const AppError = require("../middleware/AppError");
jest.mock("../middleware/AppError", () => { jest.mock("../middleware/AppError", () => {
const actualAppError = jest.requireActual("../middleware/AppError"); const actualAppError = jest.requireActual("../middleware/AppError");
@ -47,7 +45,7 @@ describe("Rooms", () => {
it("should throw error when userId is missing", async () => { it("should throw error when userId is missing", async () => {
await expect(rooms.create("test", undefined)).rejects.toThrowError( await expect(rooms.create("test", undefined)).rejects.toThrowError(
new AppError("Missing required parameter(s)", 400) new Error("Missing required parameter(s)", 400)
); );
}); });
@ -59,7 +57,7 @@ describe("Rooms", () => {
}); });
await expect(rooms.create("existing room", "12345")).rejects.toThrowError( await expect(rooms.create("existing room", "12345")).rejects.toThrowError(
new AppError("Une salle avec ce nom existe déjà", 409) new Error("Room already exists", 409)
); );
}); });
}); });
@ -210,12 +208,12 @@ describe("Rooms", () => {
const result = await rooms.roomExists(title); const result = await rooms.roomExists(title);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.collection).toHaveBeenCalledWith("rooms"); expect(db.collection).toHaveBeenCalledWith('rooms');
expect(collection.findOne).toHaveBeenCalledWith({ title }); expect(collection.findOne).toHaveBeenCalledWith({ title });
expect(result).toBe(false); expect(result).toBeFalsy();
});
}); });
});
describe("getRoomById", () => { describe("getRoomById", () => {
it("should return a room by ID", async () => { it("should return a room by ID", async () => {
@ -243,7 +241,7 @@ describe("Rooms", () => {
collection.findOne.mockResolvedValue(null); collection.findOne.mockResolvedValue(null);
await expect(rooms.getRoomById(roomId)).rejects.toThrowError( await expect(rooms.getRoomById(roomId)).rejects.toThrowError(
new AppError(`Room ${roomId} not found`, 404) new Error(`Room ${roomId} not found`, 404)
); );
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();

View file

@ -1,172 +1,179 @@
const AppError = require("../middleware/AppError");
const ObjectId = require("mongodb").ObjectId; const ObjectId = require("mongodb").ObjectId;
class Rooms { class Rooms
constructor(db) { {
this.db = db; constructor(db)
} {
this.db = db;
async create(title, userId) {
try {
if (!title || !userId) {
throw new AppError("Missing required parameter(s)", 400);
}
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const normalizedTitle = title.toLowerCase();
const existingRoom = await roomsCollection.findOne({
title: normalizedTitle,
userId: userId,
});
if (existingRoom) {
throw new AppError("Une salle avec ce nom existe déjà", 409);
}
const newRoom = {
userId: userId,
title: title,
created_at: new Date(),
};
const result = await roomsCollection.insertOne(newRoom);
return result.insertedId;
} catch (error) {
console.error("Error in create function:", error);
throw new AppError(error.message || "Internal Server Error", 500);
}
}
async getUserRooms(userId) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const result = await roomsCollection.find({ userId: userId }).toArray();
return result;
}
async getOwner(roomId) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const room = await roomsCollection.findOne({
_id: ObjectId.createFromHexString(roomId),
});
return room.userId;
}
async getContent(roomId) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
if (!ObjectId.isValid(roomId)) {
return null; // Évite d'envoyer une requête invalide
} }
const result = await roomsCollection.findOne({ _id: new ObjectId(roomId) }); async create(title, userId)
{
if (!title || !userId) {
throw new Error('Missing required parameter(s)', 400);
}
return result; await this.db.connect();
} const conn = this.db.getConnection();
const roomsCollection = conn.collection('rooms');
const normalizedTitle = title.toLowerCase();
async delete(roomId) { const existingRoom = await roomsCollection.findOne({ title: normalizedTitle, userId: userId });
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms"); if (existingRoom) {
throw new Error('Room already exists', 409);
}
const roomResult = await roomsCollection.deleteOne({ const newRoom = {
_id: ObjectId.createFromHexString(roomId), userId: userId,
}); title: title,
created_at: new Date()
};
if (roomResult.deletedCount != 1) return false; const result = await roomsCollection.insertOne(newRoom);
return true; return result.insertedId;
}
async rename(roomId, userId, newTitle) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const existingRoom = await roomsCollection.findOne({
title: newTitle,
userId: userId,
});
if (existingRoom)
throw new Error(`Room with name '${newTitle}' already exists.`);
const result = await roomsCollection.updateOne(
{ _id: ObjectId.createFromHexString(roomId), userId: userId },
{ $set: { title: newTitle } }
);
if (result.modifiedCount != 1) return false;
return true;
}
async roomExists(title) {
// Ajouter userId en paramètre
try {
await this.db.connect();
const conn = this.db.getConnection();
const existingRoom = await conn.collection("rooms").findOne({
title: title.toLowerCase(),
});
return !!existingRoom;
} catch (_error) {
throw new AppError("Erreur base de données", 500); // Encapsuler les erreurs
} }
}
async getRoomById(roomId) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms"); async getUserRooms(userId)
{
await this.db.connect();
const conn = this.db.getConnection();
const room = await roomsCollection.findOne({ const roomsCollection = conn.collection("rooms");
_id: ObjectId.createFromHexString(roomId),
});
if (!room) throw new AppError(`Room ${roomId} not found`, 404); const result = await roomsCollection.find({ userId: userId }).toArray();
return room; return result;
} }
async getRoomWithContent(roomId) { async getOwner(roomId)
const room = await this.getRoomById(roomId); {
await this.db.connect();
const conn = this.db.getConnection();
const content = await this.getContent(roomId); const roomsCollection = conn.collection("rooms");
return { const room = await roomsCollection.findOne({
...room, _id: ObjectId.createFromHexString(roomId),
content: content, });
};
}
async getRoomTitleByUserId(userId) {
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms"); return room.userId;
}
const rooms = await roomsCollection.find({ userId: userId }).toArray(); async getContent(roomId)
{
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
if (!ObjectId.isValid(roomId))
{
return null; // Évite d'envoyer une requête invalide
}
return rooms.map((room) => room.title); const result = await roomsCollection.findOne({ _id: new ObjectId(roomId) });
}
return result;
}
async delete(roomId)
{
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const roomResult = await roomsCollection.deleteOne({
_id: ObjectId.createFromHexString(roomId),
});
if (roomResult.deletedCount != 1) return false;
return true;
}
async rename(roomId, userId, newTitle)
{
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const existingRoom = await roomsCollection.findOne({
title: newTitle,
userId: userId,
});
if (existingRoom)
throw new Error(`Room with name '${newTitle}' already exists.`);
const result = await roomsCollection.updateOne(
{ _id: ObjectId.createFromHexString(roomId), userId: userId },
{ $set: { title: newTitle } }
);
if (result.modifiedCount != 1) return false;
return true;
}
async roomExists(title)
{ // Ajouter userId en paramètre
try
{
await this.db.connect();
const conn = this.db.getConnection();
const existingRoom = await conn.collection('rooms').findOne({
title: title.toLowerCase()
});
return existingRoom ? true : false;
} catch (error)
{
throw new Error(`Database error (${error})`, 500);
}
}
async getRoomById(roomId)
{
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const room = await roomsCollection.findOne({
_id: ObjectId.createFromHexString(roomId),
});
if (!room) throw new Error(`Room ${roomId} not found`, 404);
return room;
}
async getRoomWithContent(roomId)
{
const room = await this.getRoomById(roomId);
const content = await this.getContent(roomId);
return {
...room,
content: content,
};
}
async getRoomTitleByUserId(userId)
{
await this.db.connect();
const conn = this.db.getConnection();
const roomsCollection = conn.collection("rooms");
const rooms = await roomsCollection.find({ userId: userId }).toArray();
return rooms.map((room) => room.title);
}
} }
module.exports = Rooms; module.exports = Rooms;