endpoints-uzhttp
Endpoints server interpreter backed by uzhttp.
You Probably Shouldn’t Use It Because You Probably Shouldn’t Use uzhttp.
Server¶
"io.github.jkobejs" %% "endpoints-uzhttp-server" % "0.2.0"
Endpoints
¶
The Endpoints
interpreter provides intepret and interpretPure methods that can be chained using orElse
method and integrated to your uzhttp server.
For instance, given the following endpoint definition:
val items =
endpoint(
get(
path / "items" / segment[String]("category") /? qs[Option[Int]]("page")
),
ok(
jsonResponse[List[Item]],
Some("List all the items of the given category")
)
)
val itemId = segment[String]("id")
val item =
endpoint(
get(path / "item" / itemId),
wheneverFound(
ok(jsonResponse[Item], Some("The item identified by 'id'")),
Some("Item not found")
)
)
It can be implemented as follows:
val handler: PartialFunction[uzhttp.Request, ZIO[Any with Blocking, HTTPError, uzhttp.Response]] =
items.interpretPure {
case (category, page) =>
List(Item(s"first item from category $category and page $page"))
} orElse
item.interpret(id => UIO.some(Item(id.toString)))
The result is a partial function that can be integrated in your server like any other partial function that satisfies given type definition using uzhttp.server.Server
’s handleSome method.
Error handling¶
When the server processes requests, three kinds of errors can happen: the incoming request doesn’t match any endpoint, the request does match an endpoint but is invalid (e.g. one parameter has a wrong type), or an exception is thrown.
The incoming request doesn’t match any endpoint¶
In that case, since interpreters return partial function of type
PartialFunction[UzRequest, ZIO[R with Blocking, HTTPError, UzResponse]]
uzhttp server will return 404 error.
The incoming request is invalid¶
In that case, endpoints returns a “Bad Request” (400) response reporting all the errors in a JSON array. You can change this behavior by overriding the handleClientErrors method.
An exception is thrown¶
If an exception is thrown during request decoding, or when running the business logic, or when encoding the response, endpoints returns an “Internal Server Error” (500) response reporting the error in a JSON array. You can change this behavior by overriding the handleServerError method.