Skip to content

Instantly share code, notes, and snippets.

@russwyte
Created October 2, 2024 18:21
Show Gist options
  • Save russwyte/1cf305ddf861ffd62a8fbb86b8e2695a to your computer and use it in GitHub Desktop.
Save russwyte/1cf305ddf861ffd62a8fbb86b8e2695a to your computer and use it in GitHub Desktop.
package example
import zio.schema.*
import zio.http.*
import zio.http.endpoint.*
import zio.*
import zio.http.Method.*
import zio.http.codec.ContentCodec
import zio.http.codec.HeaderCodec
import zio.http.Header.ContentType
case class Foo(bars: List[Int]) derives Schema
object App extends zio.ZIOAppDefault:
val unexpected = Endpoint(POST / "unexpected").in[Foo].out[Foo]
val expected =
import zio.json.*
given fooCodec: JsonCodec[Foo] =
schema.codec.JsonCodec.jsonCodec(Foo.derived$Schema)
Endpoint(POST / "expected")
.in[Foo]
.out[Foo]
.outCodec(
ContentCodec
.content[String](MediaType.text.plain)
.transformOrFail(s => s.fromJson[Foo])(e => Right(e.toJson))
)
.outHeader(HeaderCodec.contentType)
.transformOut((foo, _) => foo)(foo =>
(foo, ContentType(MediaType.application.json))
)
val routes = Routes(
unexpected.implement(foo => ZIO.succeed(foo)),
expected.implement(foo => ZIO.succeed(foo))
)
def checkRoute(path: String, foo: Foo) =
import zio.schema.codec.JsonCodec.*
routes
.apply(
Request(
Version.`HTTP/1.1`,
POST,
URL.decode(path).toOption.get,
Headers.apply(Header.Accept(MediaType.application.json)),
Body.from(foo),
None,
None
)
)
.flatMap(_.body.asString)
def run =
for
_ <- checkRoute("/unexpected", Foo(List(1, 2, 3))).debug("unexpected")
_ <- checkRoute("/expected", Foo(List(1, 2, 3))).debug("expected")
_ <- checkRoute("/unexpected", Foo(Nil)).debug("unexpected")
_ <- checkRoute("/expected", Foo(Nil)).debug("expected")
yield ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment