Created
December 12, 2018 09:29
-
-
Save LukaJCB/cc6af61602537eaa5e28cd3dd271feb6 to your computer and use it in GitHub Desktop.
Miniserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.typelevel.miniserver | |
import cats.effect.{ExitCode, IO, IOApp} | |
import cats.implicits._ | |
import org.http4s.HttpRoutes | |
import org.http4s.dsl.io._ | |
import org.http4s.implicits._ | |
import org.http4s.circe.CirceEntityEncoder._ | |
import org.http4s.server.blaze.BlazeServerBuilder | |
import doobie.util.transactor.Transactor | |
import doobie.implicits._ | |
import doobie.postgres.implicits._ | |
import io.chrisdavenport.fuuid.doobie.implicits._ | |
import io.chrisdavenport.fuuid.circe._ | |
import io.chrisdavenport.fuuid.http4s._ | |
import io.chrisdavenport.fuuid.FUUID | |
object Server extends IOApp { | |
val xa: Transactor[IO] = Transactor.fromDriverManager[IO]( | |
"org.postgresql.Driver", "jdbc:postgresql:test;DB_CLOSE_DELAY=-1", "sa", "") | |
val service = HttpRoutes.of[IO] { | |
case req @ POST -> Root => for { | |
data <- req.as[String] | |
id <- FUUID.randomFUUID[IO] | |
_ <- sql"INSERT INTO table (id, data) VALUES ($id, $data)".update.run.transact(xa) | |
result <- Ok(id) | |
} yield result | |
case GET -> Root / FUUIDVar(id) => | |
sql"SELECT data FROM table WHERE id = ${id}".query[String].option.transact(xa).flatMap { | |
case Some(data) => Ok(data) | |
case None => NotFound("No data with this Id") | |
} | |
}.orNotFound | |
def run(args: List[String]): IO[ExitCode] = | |
BlazeServerBuilder[IO] | |
.bindHttp(8080, "localhost") | |
.withHttpApp(service) | |
.serve | |
.compile | |
.drain | |
.as(ExitCode.Success) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment