Skip to content

Instantly share code, notes, and snippets.

@Vilkina
Created March 13, 2020 18:59
Show Gist options
  • Save Vilkina/4c814758198d4246b32b56582187215b to your computer and use it in GitHub Desktop.
Save Vilkina/4c814758198d4246b32b56582187215b to your computer and use it in GitHub Desktop.
package com.oleksandrah.cakes
import com.oleksandrah.cakes.model.{Cake, Cakes, Tables}
import org.scalatra.ScalatraServlet
import org.scalatra.scalate.ScalateSupport
import slick.jdbc.H2Profile
import slick.jdbc.H2Profile.api._
import zio.{Exit, IO, Task, ZIO, _}
class CakeStore(db: H2Profile.backend.Database) extends ScalatraServlet with ScalateSupport {
val runtime = new DefaultRuntime {}
override def renderResponse(a: Any): Unit = {
if (a.isInstanceOf[ZIO[_, _, _]]) {
val exit: Exit[Throwable, Any] =
runtime.unsafeRunSync(a.asInstanceOf[Task[Any]])
val result: Any = exit
.fold(
cause =>
cause.failureOption orElse cause.dieOption match {
case Some(t: Throwable) => throw t
case _ =>
println("---" + cause)
None
},
x => x
)
super.renderResponse(result)
} else {
super.renderResponse(a)
}
}
def exec[T](action: DBIO[T]): Task[T] = ZIO.fromFuture(implicit executionContext => db.run(action))
def getCakes: Task[Map[Int, Cake]] = {
for {
cakes <- exec(Tables.cakes.result)
} yield cakes.map(cake => cake.id -> cake).toMap
}
get("/") {
contentType = "text/html"
val getCake = for {
cakes <- getCakes
} yield jade("/index", "cakes" -> cakes.values.toList.sortBy(_.baked))
runtime.unsafeRun(getCake.orDie)
}
post("/new") {
val test = for {
cakes <- getCakes
id = cakes.size
_ <- exec(Tables.cakes += Cake(id, params.get("cakes").get, false))
r <- ZIO(redirect("/"))
} yield r
runtime.unsafeRun(test.orDie)
}
get("/:id/baked") {
val id = params("id").toInt
exec(Tables.cakes.filter(_.id === id).map(_.baked).update(true))
redirect("/")
}
get("/:id/delete") {
val id = params("id").toInt
exec(Tables.cakes.filter(_.id === id).delete)
redirect("/")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment