How could I add status
field into json response in Tapir?
Assume, I have endpoint which looks like this:
private lazy val endpoint =
endpoint
.post
.in(jsonBody[Entity])
.out(jsonBody[ChangedEntity])
.errorOut(jsonBody[Error])
.serverLogic {
changeEntity
}
def changeEntity(e: Entity): Future[Either[Error, ChangedEntity]] = ...
case class Error(
msg: String,
code: Int,
)
case class ChangedEntity(
id: Int,
data: String,
)
My Circe encoder is
implicit def encodeResponse[R](implicit
left: Encoder[Error],
right: Encoder[R]
): Encoder[Either[Error, R]] = {
o: Either[Error, R] =>
o.fold(_.asJson, _.asJson).mapObject(_.+:(status, o.isRight.asJson))
}
I'd like to get json like this:
//on success
{
"status": true,
"id": 42,
"data": "some data
}
//on error
{
"status": false
"msg": "error happenend",
"code": 12345
}
If I'll use that circe encoder in Akka Http it will encode status field. How can I achieve the same idea in Tapir? Should I use custom codec somehow?