diff --git a/src/main/resources/postgres.conf b/src/main/resources/postgres.conf new file mode 100644 index 0000000..5de116e --- /dev/null +++ b/src/main/resources/postgres.conf @@ -0,0 +1,3 @@ +username = "postgres" +password = "mysecretpassword" +url = "jdbc:postgresql://localhost:5432/weather-tool" \ No newline at end of file diff --git a/src/main/scala/app/Main.scala b/src/main/scala/app/Main.scala index 14a4ded..ad996ec 100644 --- a/src/main/scala/app/Main.scala +++ b/src/main/scala/app/Main.scala @@ -2,25 +2,16 @@ package app import cats.effect._ import cats.implicits.catsSyntaxTuple2Parallel -import db.Main.transactor -import db.{DataService, FileService, PostgresService} -import doobie.Transactor +import db.{DBConnection, DataService, FileService, PostgresService} import fetch.{FetchService, FileFetchScheduler} import server.Server object Main extends IOApp { - - def transactor[F[_] : Async]: Transactor[F] = Transactor.fromDriverManager[F]( - "org.postgresql.Driver", - "jdbc:postgresql://localhost:5432/weather-tool", - "postgres", - "mysecretpassword" - ) def run(args: List[String]): IO[ExitCode] = { - val xa = transactor[IO] - for { - postgresService <- PostgresService.of(xa) + transactor <- DBConnection.transactor[IO] + postgresService <- PostgresService.of(transactor) + _ <- postgresService.createWeatherTable // create table if it does not exists fileService <- FileService.of dataService <- DataService.of(fileService, postgresService) diff --git a/src/main/scala/db/DBConnection.scala b/src/main/scala/db/DBConnection.scala new file mode 100644 index 0000000..93bec56 --- /dev/null +++ b/src/main/scala/db/DBConnection.scala @@ -0,0 +1,27 @@ +package db + +import cats.effect.{Async, IO} +import doobie.Transactor +import pureconfig._ +import pureconfig.generic.auto._ +import pureconfig.error.ConfigReaderFailures + +case class PostgresConfig(username: String, password: String, url: String) + +object DBConnection { + private def loadPostgresConfig: Either[ConfigReaderFailures, PostgresConfig] = { + ConfigSource.resources("postgres.conf").load[PostgresConfig] + } + + def transactor[F[_] : Async]: IO[Transactor[F]] = { + loadPostgresConfig match { + case Right(config) => IO(Transactor.fromDriverManager[F]( + "org.postgresql.Driver", + config.url, + config.username, + config.password + )) + case Left(errors) => IO.raiseError(new RuntimeException(s"Failed to load config: $errors")) + } + } +} diff --git a/src/main/scala/db/PostgresService.scala b/src/main/scala/db/PostgresService.scala index 3c66b29..8ac3526 100644 --- a/src/main/scala/db/PostgresService.scala +++ b/src/main/scala/db/PostgresService.scala @@ -75,7 +75,7 @@ class PostgresService(transactor: Transactor[IO], log: Logger[IO]) extends DataS } } - def createWeatherTable(): IO[Int] = { + def createWeatherTable: IO[Int] = { for { createTableSql <- getResourceContent("/db/create_weather_table.sql") result <- Update0(createTableSql, None).run.transact(transactor)