Skip to content

Commit

Permalink
Add demo
Browse files Browse the repository at this point in the history
  • Loading branch information
kubukoz committed Jan 25, 2024
1 parent 88da8da commit 9336384
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
1 change: 1 addition & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ val commonSettings = Seq(
scalacOptions ++= Seq(
"-Wunused:all"
),
Test / fork := true,
)

lazy val core = project
Expand Down
66 changes: 66 additions & 0 deletions core/src/test/scala/respectfully/Demo.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package respectfully

import cats.effect.IO
import cats.effect.IOApp
import io.circe.Codec
import io.circe.Decoder
import io.circe.Encoder
import org.http4s.HttpApp
import org.http4s.Response
import org.http4s.Uri
import org.http4s.circe.CirceEntityCodec._
import org.http4s.client.Client
import org.http4s.ember.client.EmberClientBuilder
import org.http4s.ember.server.EmberServerBuilder

@annotation.experimental
object Demo extends IOApp.Simple {

case class User(id: Int, name: String, age: Int) derives Codec.AsObject

trait Api {
def getUsers(): IO[List[User]]
def getUser(id: Int): IO[User]
def createUser(user: User): IO[User]
def updateUser(user: User): IO[User]
def deleteUser(id: Int): IO[Unit]
}

given API[Api] = API.derived

val impl: Api =
new Api {
def getUsers(): IO[List[User]] = IO(List(User(1, "John", 20)))
def getUser(id: Int): IO[User] = IO(User(1, "John", 20))
def createUser(user: User): IO[User] = IO(user)
def updateUser(user: User): IO[User] = IO(user)
def deleteUser(id: Int): IO[Unit] = IO.unit
}

def router(impl: Api): HttpApp[IO] = API[Api].toRoutes(impl)

def client(c: Client[IO], base: Uri): Api = API[Api].toClient(c, base)

import com.comcast.ip4s._

def run: IO[Unit] = EmberServerBuilder
.default[IO]
.withHttpApp(router(impl))
.withHost(host"0.0.0.0")
.withPort(port"8080")
.withErrorHandler { case e => IO.consoleForIO.printStackTrace(e) *> IO.raiseError(e) }
.build
.use { server =>
EmberClientBuilder.default[IO].build.use { c =>
val apiClient = client(c, server.baseUri)

apiClient
.getUser(42)
.flatMap(IO.println(_)) *>
apiClient
.getUsers()
.flatMap(IO.println(_))
}
}

}

0 comments on commit 9336384

Please sign in to comment.