Skip to content

Instantly share code, notes, and snippets.

@tg44

tg44/tapir.sc Secret

Last active June 24, 2020 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tg44/8649649b01dfefde2c55428f40d29bf3 to your computer and use it in GitHub Desktop.
Save tg44/8649649b01dfefde2c55428f40d29bf3 to your computer and use it in GitHub Desktop.
Tapir strange
import $ivy.`com.typesafe.akka::akka-stream-typed:2.6.4`
import $ivy.`com.typesafe.akka::akka-http:10.1.11`
import $ivy.`org.typelevel::cats-core:2.0.0`
import $ivy.`com.softwaremill.sttp.tapir::tapir-akka-http-server:0.12.25`
import $ivy.`com.softwaremill.sttp.tapir::tapir-json-circe:0.12.25`
import $ivy.`io.circe::circe-generic:0.13.0`
import $ivy.`ch.qos.logback:logback-classic:1.2.3`
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import cats.data.EitherT
import cats.implicits._
import sttp.tapir._
import sttp.tapir.json.circe._
import io.circe.generic.auto._
import org.slf4j.{Logger, LoggerFactory}
import concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
case class EmptyResponse()
object StaticServer {
val emptyResponse: EndpointIO[Unit] =
jsonBody[EmptyResponse].map { x =>
print("b "); println(x); ()
} { x =>
print("a "); println(x); EmptyResponse()
}
implicit class FutureNumToEmpty[A: Numeric](f: => Future[A]) {
def mapToBadRequestOrUnit(implicit executionContext: ExecutionContext): EitherT[Future, Unit, Unit] = {
println("here")
EitherT.right[Unit](f).ensure({})(implicitly[Numeric[A]].toInt(_) == 1).map(_ => ())
}
}
implicit val logger: Logger = LoggerFactory.getLogger("logger")
implicit val as = ActorSystem("testAS")
implicit val ec = as.dispatcher
def testFun(l: Long) = {
println(l)
Future.successful(l)
}
val ep = endpoint.get
.tag("Test")
.in("test")
.in(path[Int])
.out(emptyResponse)
.serverLogic { l =>
println(l)
testFun(l).mapToBadRequestOrUnit.value
}
import sttp.tapir.server.akkahttp._
import akka.http.scaladsl.server.Directives._
val route = ep.toRoute
val r = Http()
.bindAndHandle(route, "0.0.0.0", 9000)
.map(binding => {
println(s"Server started")
println(binding)
binding
})
.flatMap( _ =>
Http().singleRequest(HttpRequest(uri = "http://localhost:9000/test/1")).map(x => println(x.status))
)
}
Await.result(StaticServer.r, 300.seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment