scalafinagle

Finch jsonBody custom parameter conversion


We are using jsonbody to convert json payload in the body to a scala case class:

val domainObject: Endpoint[String] = post("domain" :: jsonBody[DomainEvent] :: some_more :: 

Now I want to limit the length of one the fields to let's say 200 characters. Of course I can copy the retrieved DomainEvent with the fields' value truncated to 200 characters but that seems a bit inefficient. Is there a way to easily change jsonBody's behaviour to incorporate this effect?


Solution

  • This is a very custom use case and Finch doesn't support it. It's custom for at least three reasons that I can think of:

    1. You're not validating the input; instead, you accept any length, but then you modify it to be 200 characters max.
    2. It's not enforced on the whole body, but only on one specific field.
    3. It's not defined by the size in bytes (like Content-Length header), but in the length of characters.

    But you could achieve this on the decoding level, which is still better than truncating in the domain model (case class). See the documentation on custom decoders.

    At some point you will need to implement a function String => Try[DomainEvent] and this is where you can plug in your implementation - after reading the JSON field that needs to be truncated, shorten it to 200 characters and use that when populating the DomainEvent case class. This way the case class itself doesn't need to know anything about truncating; it's endpoint-specific, and it happens in the layer which decodes the JSON body into the case class.