From cebb00cc1b405715558b849e7f309e8a1aea03d8 Mon Sep 17 00:00:00 2001
From: Felipe D'Abrantes <felidabrantes@gmail>
Date: Fri, 21 Apr 2023 23:44:07 +0100
Subject: [PATCH] Add delete method to base repository

---
 .../app/repositories/Repository.scala         |  9 +++++++
 .../app/utils/MongoConnection.scala           | 24 ++++++++++++++++++-
 2 files changed, 32 insertions(+), 1 deletion(-)

diff --git a/backend-services/feed-service/app/repositories/Repository.scala b/backend-services/feed-service/app/repositories/Repository.scala
index b6eacb9b..43ea68e2 100644
--- a/backend-services/feed-service/app/repositories/Repository.scala
+++ b/backend-services/feed-service/app/repositories/Repository.scala
@@ -126,4 +126,13 @@ class Repository[T: ClassTag](databaseName: String, collectionName: String) {
     def updateOne(documentId: ObjectId, updates: Seq[Bson]): Future[Unit] = {
         MongoConnection.updateOne[T](collection, documentId, updates)
     }
+
+    /**
+     * Delete one document from the collection that matches the given ID.
+     * 
+     * @param documentId The ID of the document to delete.
+     */
+    def deleteOne(documentId: ObjectId): Future[Unit] = {
+        MongoConnection.deleteOne(collection, documentId)
+    }
 }
diff --git a/backend-services/feed-service/app/utils/MongoConnection.scala b/backend-services/feed-service/app/utils/MongoConnection.scala
index 6355414a..da1ac5b8 100644
--- a/backend-services/feed-service/app/utils/MongoConnection.scala
+++ b/backend-services/feed-service/app/utils/MongoConnection.scala
@@ -2,7 +2,7 @@ package utils
 
 import org.mongodb.scala.{MongoClient, MongoDatabase, MongoCollection}
 import org.mongodb.scala.model.{Filters}
-import com.mongodb.client.result.{InsertOneResult, UpdateResult}
+import com.mongodb.client.result.{InsertOneResult, UpdateResult, DeleteResult}
 
 import org.bson.conversions.Bson
 import org.bson.types.ObjectId
@@ -118,4 +118,26 @@ object MongoConnection {
             }
         })
     }
+
+    /**
+     * Delete one document from the collection that matches the given ID.
+     * 
+     * @param collection The MongoCollection instance the document is in.
+     * @param documentId The ID of the document to delete.
+     * @throws RuntimeException if the delete was not acknowledged by the database.
+     */
+    def deleteOne[T](collection: MongoCollection[T], documentId: ObjectId): Future[Unit] = {
+        val filter: Bson = Filters.equal[ObjectId]("_id", documentId)
+        val futureResult: Future[DeleteResult] =  collection.deleteOne(filter).toFuture()
+        
+        futureResult.map[Unit]((result: DeleteResult) => {
+            if (!result.wasAcknowledged()) {
+                throw new RuntimeException("Delete was not acknowledged")
+            }
+
+            if (result.getDeletedCount() == 0) {
+                throw new RuntimeException("Delete was not acknowledged")
+            }
+        })
+    }
 }
-- 
GitLab