feat: loading data from api on start
This commit is contained in:
parent
f383085910
commit
9bdf180f97
|
@ -6,10 +6,10 @@ val toolkitTest = "org.scala-lang" %% "toolkit-test" % toolkitV
|
|||
|
||||
val cask = "com.lihaoyi" %% "cask" % "0.9.1"
|
||||
val mainargs = "com.lihaoyi" %% "mainargs" % "0.5.4"
|
||||
val requests = "com.lihaoyi" %% "requests" % "0.8.0"
|
||||
|
||||
ThisBuild / scalaVersion := "3.2.2"
|
||||
libraryDependencies += cask
|
||||
libraryDependencies += mainargs
|
||||
libraryDependencies ++= Seq(cask, mainargs, requests)
|
||||
libraryDependencies += toolkit
|
||||
libraryDependencies += (toolkitTest % Test)
|
||||
|
||||
|
|
|
@ -5,20 +5,27 @@ import org.thymeleaf.TemplateEngine
|
|||
import org.thymeleaf.context.Context
|
||||
import cask.model.Response
|
||||
import mainargs.{main, arg, ParserForMethods, Flag}
|
||||
import scala.util.Try
|
||||
|
||||
object MinimalApplication extends cask.Routes{
|
||||
object MinimalApplication extends cask.Routes {
|
||||
|
||||
@main
|
||||
def run(
|
||||
@arg(name="port", short='p', doc="Port on which server will start service")
|
||||
@arg(
|
||||
name = "port",
|
||||
short = 'p',
|
||||
doc = "Port on which server will start service"
|
||||
)
|
||||
portArg: Int = 8080,
|
||||
@arg(name="host", doc="Host on which server will start serving")
|
||||
@arg(name = "host", doc = "Host on which server will start serving")
|
||||
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(countries = countriesDb ))
|
||||
override def allRoutes: Seq[cask.main.Routes] = Seq(
|
||||
Routes(countries = countriesDb)
|
||||
)
|
||||
override def port: Int = portArg
|
||||
override def host: String = hostArg
|
||||
}
|
||||
|
@ -26,14 +33,23 @@ object MinimalApplication extends cask.Routes{
|
|||
}
|
||||
|
||||
def loadCountries() = {
|
||||
val countries: List[Country] = upickle.default.read[List[Country]](
|
||||
val defaultCountriesData: List[Country] =
|
||||
upickle.default.read[List[Country]](
|
||||
scala.io.Source.fromResource("temporary/all.json").getLines().mkString,
|
||||
true
|
||||
)
|
||||
countries
|
||||
val apiDataRequest = requests.get("https://restcountries.com/v3.1/all")
|
||||
val apiData = Try(
|
||||
upickle.default.read[List[Country]](apiDataRequest.text(), true)
|
||||
)
|
||||
if (apiData.isFailure)
|
||||
println(s"> data load failed ${apiData}")
|
||||
else
|
||||
println(s"> api data load is successful")
|
||||
|
||||
apiData.toOption.getOrElse(defaultCountriesData)
|
||||
}
|
||||
|
||||
def main(args: Array[String]): Unit = ParserForMethods(this).runOrExit(args)
|
||||
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue