Skip to content

Less strict declarative style Endpoint implementation #3301

@pocorall

Description

@pocorall

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions