Skip to content

Commit

Permalink
Update sample http server with db-test
Browse files Browse the repository at this point in the history
  • Loading branch information
mikolajkapica committed Jun 23, 2024
1 parent 474e328 commit 9f876f8
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 22 deletions.
24 changes: 3 additions & 21 deletions api/src/main/scala/Database.scala
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
import org.mongodb.scala.Document
import org.mongodb.scala.MongoClient
import org.mongodb.scala.MongoCollection

import tour.Helpers._
import org.mongodb.scala.MongoDatabase

object Database {

def test(): Unit =
println("Connecting to MongoDB...")
val mongoClient = MongoClient(sys.env("DATABASE_URL"))
val database = mongoClient.getDatabase("mydb")
database.createCollection("test2")
val collection: MongoCollection[Document] = database.getCollection("test2")

val document = Document(
"name" -> "MongoDB",
"type" -> "database",
"count" -> 1,
"info" -> Document("x" -> 203, "y" -> 102),
)

collection.insertOne(document).results()
collection.find().printResults()
println("Document inserted")
def connect(db_name: String): MongoDatabase = MongoClient(sys.env("DATABASE_URL"))
.getDatabase(db_name)

}
2 changes: 1 addition & 1 deletion api/src/main/scala/Helpers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ object Helpers {
def headResult() = Await.result(observable.head(), Duration(10, TimeUnit.SECONDS))

def printResults(initial: String = ""): Unit = {
if (initial.length > 0)
if (initial.nonEmpty)
print(initial)
results().foreach(res => println(converter(res)))
}
Expand Down
18 changes: 18 additions & 0 deletions api/src/main/scala/Router.scala
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Database.connect
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.server.Directives.complete
Expand All @@ -6,6 +7,8 @@ import akka.http.scaladsl.server.Directives.path
import akka.http.scaladsl.server.Directives.pathSingleSlash
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._enhanceRouteWithConcatenation
import org.mongodb.scala.bson.collection.immutable.Document
import tour.Helpers._

object Router {

Expand All @@ -24,6 +27,21 @@ object Router {
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>OK</h1>"))
}
} ~
path("db-test") {
get {
val db = connect("test")
db.createCollection("test")
db.getCollection("test").insertOne(Document("name" -> "test")).results()
val result = db.getCollection("test").find().results().map(_.toJson).mkString(", ")

complete(
HttpEntity(
ContentTypes.`text/html(UTF-8)`,
s"<h1>DB Test</h1><p>Result: $result</p>",
)
)
}
}

}

0 comments on commit 9f876f8

Please sign in to comment.