Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to add support for custom (or derived from schema) encoding function to derived Scala 3 enumeration validator? #4132

Closed
alexander-klimov opened this issue Nov 5, 2024 · 2 comments · Fixed by #4175

Comments

@alexander-klimov
Copy link
Contributor

alexander-klimov commented Nov 5, 2024

Feature request

Let Tapir users customise (or somehow derive from the Schema) the encode function of the enumeration Validator, so it is in line with the one provided to Schema using derivedEnumeration[T](encode = Some(...))

Description

Currently (in both Tapir 1.9.9 and on master branch), the macro for Scala 3 enumeration Validator sets encode function to None (code reference). If enumeration validation fails, the list of possible enumeration values in the failure message is encoded differently compared to how it's done in Schema if custom encode is provided.

Use case

Suppose I have an enumeration, with derived Schema

enum PieType(val index: Int, val name: String) {
  case Apple                 extends PieType(1, "apple")
  case Orange              extends PieType(2, "orange")
  case BananaCustard extends PieType(3, "banana-custard")
}

given Schema[PieType] = Schema.derivedEnumeration[PieType](encode = Some(_.name))

Now, if I have PieType as, for example, query parameter called type, and I call my API with an unsupported value (e.g. berry), then the response I get would be

Invalid value for: path parameter tpe (expected value to be one of (Apple, Orange, BananaCustard), but got: \"berry\")

which doesn't align with the OpenAPI spec that is generated from the endpoint (because Schema.encode is used there).

Current workaround

Override toString method of the enumeration type, but that is not always acceptable

enum PieType(val index: Int, val name: String) {
  ...
  override def toString: String = name
}
@adamw
Copy link
Member

adamw commented Nov 18, 2024

The validator is later updated (see here, but the updated validator wasn't later used to format error messages. This should be fixed in #4175. I assume error messages where the only problem, otherwise please let us know :)

@alexander-klimov
Copy link
Contributor Author

Great, thanks Adam 🙂
Glad it was only a matter of making a tiny change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants