From cac3e219b4bbfe960e24c7cdf5e4e232903d0e4f Mon Sep 17 00:00:00 2001
From: Felipe D'Abrantes <felidabrantes@gmail>
Date: Mon, 10 Apr 2023 02:52:05 +0100
Subject: [PATCH] Add an object to run HTTP calls

---
 .../feed-service/app/models/HttpCall.scala    | 43 +++++++++++++++++++
 backend-services/feed-service/build.sbt       |  2 +
 2 files changed, 45 insertions(+)
 create mode 100644 backend-services/feed-service/app/models/HttpCall.scala

diff --git a/backend-services/feed-service/app/models/HttpCall.scala b/backend-services/feed-service/app/models/HttpCall.scala
new file mode 100644
index 00000000..0ccb752d
--- /dev/null
+++ b/backend-services/feed-service/app/models/HttpCall.scala
@@ -0,0 +1,43 @@
+package models
+
+import akka.actor.ActorSystem
+import akka.stream.{Materializer, SystemMaterializer}
+import play.api.libs.ws.ahc.{StandaloneAhcWSClient}
+import play.api.libs.json.JsValue
+
+import scala.concurrent.Future
+import scala.concurrent.ExecutionContext.Implicits.global
+
+
+object HttpCall {
+
+    /**
+     * Fetches the response of a GET request to the given URL.
+     * 
+     * @param url The URL of the request.
+     * 
+     * @return a Future containing the response body as a JSON.
+     */
+    def get(url: String): Future[JsValue] = {
+        // Create ActorSystem for thread and streaming management
+        implicit val system: ActorSystem = ActorSystem()
+
+        // Materializer ensures streams are executed correctly and resources are managed efficiently
+        implicit val materializer: Materializer = SystemMaterializer(system).materializer
+
+        // Create the standalone WS client
+        val wsClient: StandaloneAhcWSClient = StandaloneAhcWSClient()
+
+        // Call API and fetch response
+        val response: Future[JsValue] = wsClient.url(url).get().map { response =>
+          val statusText: String = response.statusText
+          println(s"Got a response: $statusText")
+          response.body[JsValue]
+        }
+
+        // Close WSClient and terminate ActorSystem
+        response
+            .andThen { case _ => wsClient.close() }
+            .andThen { case _ => system.terminate() }
+    }
+}
diff --git a/backend-services/feed-service/build.sbt b/backend-services/feed-service/build.sbt
index 109e18bd..e42fe9c6 100644
--- a/backend-services/feed-service/build.sbt
+++ b/backend-services/feed-service/build.sbt
@@ -18,3 +18,5 @@ libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "5.0.0
 // Adds additional packages into conf/routes
 // play.sbt.routes.RoutesKeys.routesImport += "com.daily.binders._"
 libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "4.3.0"
+libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.8.10"
+libraryDependencies += "com.typesafe.play" %% "play-ahc-ws-standalone" % "2.1.10"
-- 
GitLab