Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Less strict declarative style Endpoint implementation #3301

Open
pocorall opened this issue Feb 12, 2025 · 0 comments
Open

Less strict declarative style Endpoint implementation #3301

pocorall opened this issue Feb 12, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@pocorall
Copy link

pocorall commented Feb 12, 2025

When I tried migrate my imperative style Route implementations to declarative style, I was frustrated by:

  1. cannot access Request object
  2. cannot return Response object
  3. exceptions must be handled using codec, it isn't falls through and catched with Routes.handleErrorCause later.

I know that this is intentional design decision. Accessing directly to Request and Response is discouraged. However, access to these objects is necessary at least for migration purpose.

As a motivating toy example, refer to this code:

object EndpointExample extends ZIOAppDefault:
  class NoProblemException(message: String) extends Exception(message)

  private val myEndpoint1 =
    Endpoint(Method.GET / "my-endpoint1").query(HttpCodec.query[Option[String]]("id"))
	  .query(HttpCodec.query[String]("name")).out[String]

  private def myRoutes = Routes(
    myEndpoint1.looseImplement { (maybeId: Option[String], name: String, req: Request) => // I hope this work
      ZIO.fail(new NoProblemException(s"my-endpoint1 $maybeId $name, requested from ${req.remoteAddress}"))
	  // alternatively, the code below should also work
	  // ZIO.succeed(Response.text("OK with Response object"))
  })

  def errorProcessor(cause: Cause[Any]): Response =
    cause.failureOrCause match
      case Left(failure) => failure match
        case i: NoProblemException => Response.json(s"""{"message": "${i.getMessage}"}""")
        case i: Throwable => Response.text("My custom response")
      case Right(cause) => Response.fromCause(cause)

  def run: ZIO[Any, Throwable, Any] =
    Server.serve(myRoutes.handleErrorCause(errorProcessor)).provide(Server.default)

I hope a new method Endpoint.looseImplement would provide this generous access to Request, Response, and ZIO.fail handling from Routes.handleErrorCause.

@pocorall pocorall added the enhancement New feature or request label Feb 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant