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 0000000000000000000000000000000000000000..0ccb752d7d34a40d51e6dbc06a0b771586784ac8 --- /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 109e18bda65e4fb9c84c9e157b8db290a694583a..e42fe9c65f8aa4ac7c87ce9f18c2b68873419c91 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"