feat: loading country data from resourse json

This commit is contained in:
efim 2023-09-23 09:31:04 +00:00
parent 73804a0ed4
commit d300d5c16b
5 changed files with 43 additions and 5 deletions

View File

@ -0,0 +1,2 @@
version = "3.7.10"
runner.dialect = scala3

View File

@ -0,0 +1,27 @@
package example
import upickle.default._
final case class Country(
name: String,
alpha3Code: String,
nativeName: String = "",
population: Int,
region: String,
subregion: String,
capital: String = "",
topLevelDomain: Option[String], // maybe optional?
currencies: List[Currency] = List.empty,
languages: List[Language],
borders: List[String] = List.empty,
) derives ReadWriter
final case class Currency(
code: String,
name: String
) derives ReadWriter
final case class Language(
name: String,
nativeName: String = ""
) derives ReadWriter

View File

@ -16,14 +16,23 @@ object MinimalApplication extends cask.Routes{
hostArg: String = "localhost"
) = {
println(s"Will start server on ${hostArg}:${portArg}")
val countriesDb = loadCountries()
val server = new cask.Main {
override def allRoutes: Seq[cask.main.Routes] = Seq(Routes())
override def allRoutes: Seq[cask.main.Routes] = Seq(Routes(countries = countriesDb ))
override def port: Int = portArg
override def host: String = hostArg
}
server.main(Array.empty)
}
def loadCountries() = {
val countries: List[Country] = upickle.default.read[List[Country]](
scala.io.Source.fromResource("temporary/data.json").getLines().mkString,
true
)
countries
}
def main(args: Array[String]): Unit = ParserForMethods(this).runOrExit(args)

View File

@ -6,8 +6,7 @@ import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
import org.thymeleaf.templatemode.TemplateMode
case class Routes()(implicit cc: castor.Context, log: cask.Logger)
case class Routes(countries: List[Country])(implicit cc: castor.Context, log: cask.Logger)
extends cask.Routes {
def buildTemplateEngine(): TemplateEngine = {
@ -27,9 +26,10 @@ case class Routes()(implicit cc: castor.Context, log: cask.Logger)
@cask.get("/")
def hello() = {
val context = new Context()
val yo = engine.process("index", context)
val indexPage = engine.process("index", context)
Response(
yo,
indexPage,
headers = Seq("Content-Type" -> "text/html; charset=utf-8")
)
}