Last active
February 28, 2018 07:18
-
-
Save mathieuancelin/6e247dfa4c42c869ab98f164b6e51657 to your computer and use it in GitHub Desktop.
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 app | |
import cats.Applicative | |
import cats.effect._ | |
import cats.implicits._ | |
import fs2.StreamApp.ExitCode | |
import fs2.{Stream, StreamApp} | |
import io.circe._ | |
import io.circe.generic.semiauto._ | |
import org.http4s.circe._ | |
import org.http4s.dsl.Http4sDsl | |
import org.http4s.headers.`Content-Type` | |
import org.http4s.server.blaze.BlazeBuilder | |
import org.http4s.{HttpService, MediaType} | |
case class User(id: String, name: String) | |
object User { | |
implicit val UserEncoder: Encoder[User] = deriveEncoder[User] | |
implicit val SeqOfUserEncoder: Encoder[Seq[User]] = Encoder.encodeSeq(UserEncoder) | |
} | |
class UsersRepository[F[_]: Applicative] { | |
def findAll(): F[Seq[User]] = | |
Seq( | |
User("1", "Billy"), | |
User("2", "Bobby"), | |
).pure[F] | |
} | |
object Users { | |
def endpoints[F[_]: Effect](repo: UsersRepository[F]): HttpService[F] = | |
new Users[F](repo).endpoints() | |
} | |
class Users[F[_]: Effect](repo: UsersRepository[F]) extends Http4sDsl[F] { | |
def endpoints(): HttpService[F] = | |
HttpService[F] { | |
case req @ GET -> Root / "users" => { | |
for { | |
users <- repo.findAll() | |
resp <- Ok(User.SeqOfUserEncoder(users)) | |
.putHeaders(`Content-Type`(MediaType.`application/json`)) | |
} yield resp | |
} | |
} | |
} | |
object Application extends StreamApp[IO] { | |
import scala.concurrent.ExecutionContext.Implicits.global | |
override def stream(args: List[String], shutdown: IO[Unit]): Stream[IO, ExitCode] = { | |
createStream[IO](args, shutdown) | |
} | |
def createStream[F[_]](args: List[String], shutdown: F[Unit])(implicit E: Effect[F]): Stream[F, ExitCode] = { | |
for { | |
_ <- Stream(()) | |
repo = Users.endpoints[F](new UsersRepository[F]) | |
// repo <- Stream.eval(E.pure(Users.endpoints[F](new UsersRepository[F]))) | |
exitCode <- BlazeBuilder[F] | |
.bindHttp(8080, "0.0.0.0") | |
.mountService(repo, "/") | |
.serve | |
} yield exitCode | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment