Hi all, I want to accept a sealed class in a POST...
# ktor
k
Hi all, I want to accept a sealed class in a POST body, and I'd like to have nice validation messages if there is a problem. So I have classes like this:
Copy code
@Serializable
data class Request(
  val constraints: List<Constraint>
  ...
)

@Serializable
sealed class Constraint

@Serializable
object Overlap : Constraint()

@Serializable
data class Overtime(val maxTime: Int) : Constraint()
If someone sends a request that has an invalid
Constraint
, I would like a nice message like:
Copy code
<some_bogus_constraint> is not a valid constraint. Valid constraints are: [Overlap, Overtime]
or
Copy code
Overtime constraint requires <maxTime>, but it was not provided
How can I accomplish this?
I am able to accept the sealed class, but if there is an issue, it gives a cryptic "failed to convert request body" exception that exposes internal implementation details.
r
This is not supported. One way of doing it, which I don't like, is to have a weak implementation of your model with everything nullable and loosely typed (e.g. String for enums) and then have a function converting your weak model to your actual model, throwing better, more explicit exceptions. Having weak implementations of all those models and all those validation functions is kinda heavy to maintain though, so now I prefer to just return 400 and have stellar documentation on what's expected.
👍 1
k
What do you use to make the stellar documentation? I tried messing with openAPI and automatic generation, but decided to do it myself from scratch. Doing it myself, I am able to give exactly the experience I want, but it is a lot of effort.
r
I'm using this https://tegral.zoroark.guru/docs/modules/core/openapi/ktor, helps you generate OpenAPI from code. I'm using Ktor Resources. I define each
@Resource
in its own file with its full path (I'm not using the "parent" thing, makes it harder to understand for newcomers), and then inside each resource I have my payload model, response model and OpenAPI documentation
k
This looks nice 👍 . Thank you for your help!