From 3975dc834c159cb882e1ed18bb783e2e771a20cb Mon Sep 17 00:00:00 2001
From: Felipe D'Abrantes <felidabrantes@gmail>
Date: Tue, 14 Mar 2023 23:44:39 +0000
Subject: [PATCH] Create a MongoDB test endpoint

---
 .../app/controllers/MongoTestController.scala | 49 +++++++++++++++++++
 backend-services/feed-service/conf/routes     |  2 +
 2 files changed, 51 insertions(+)
 create mode 100644 backend-services/feed-service/app/controllers/MongoTestController.scala

diff --git a/backend-services/feed-service/app/controllers/MongoTestController.scala b/backend-services/feed-service/app/controllers/MongoTestController.scala
new file mode 100644
index 00000000..c086129a
--- /dev/null
+++ b/backend-services/feed-service/app/controllers/MongoTestController.scala
@@ -0,0 +1,49 @@
+package controllers
+
+import javax.inject._
+import play.api._
+import play.api.mvc._
+
+import models.MongoDBClient
+import org.mongodb.scala.{Document}
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.{Future, Await, TimeoutException}
+import scala.concurrent.duration._
+
+/**
+ * This controller creates an `Action` to handle HTTP MongoDB requests.
+ */
+@Singleton
+class MongoTestController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {
+
+    /**
+    * Create an Action to test the Mongo Client.
+    */
+    def index() = Action { implicit request: Request[AnyContent] =>
+        println("MongoController")
+
+        var database_name = "{DATABASE_NAME}"
+        var collection_name = "{COLLECTION_NAME}"
+
+        var mongo = new MongoDBClient()
+
+        // Sequentially waits for Future objects to complete before calling next method
+        val result: Future[Seq[Document]] = for {
+            db <- mongo.getDatabase(database_name)
+            collection <- mongo.getCollection(db, collection_name)
+            findResult <- mongo.find(collection)
+        } yield findResult
+
+
+        try {
+            // Wait for 10 seconds for the Future to complete
+            val resultCompleted = Await.result(result, 4.seconds)
+
+            val jsonResult: Seq[String] = resultCompleted.map(doc => doc.toJson())
+            Ok(jsonResult.toString())
+        } catch {
+            case e: TimeoutException =>
+                BadRequest("Request timed out")
+        }
+    }
+}
diff --git a/backend-services/feed-service/conf/routes b/backend-services/feed-service/conf/routes
index 60e8169b..c987e313 100644
--- a/backend-services/feed-service/conf/routes
+++ b/backend-services/feed-service/conf/routes
@@ -8,3 +8,5 @@ GET     /                           controllers.HomeController.index()
 
 # Map static resources from the /public folder to the /assets URL path
 GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)
+
+GET     /mongo_test                 controllers.MongoTestController.index()
-- 
GitLab