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

Use correct validator when creating an enum codec so that error messages are rendered correctly #4175

Merged
merged 1 commit into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class CreateDerivedEnumerationCodec[L, T](validator: Validator.Enumeration[T], s
.mapDecode(s =>
decode(s) match {
case Some(value) => DecodeResult.Value(value)
case None => DecodeResult.InvalidValue(List(ValidationError(validator, s)))
case None => DecodeResult.InvalidValue(List(ValidationError(v, s)))
}
)(encode)
.schema(schemaAnnotations.enrich(s))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// {cat=Custom types; effects=Direct; server=Netty}: A query parameter which maps to a Scala 3 enum (enumeration)

//> using dep com.softwaremill.sttp.tapir::tapir-core:1.11.9
//> using dep com.softwaremill.sttp.tapir::tapir-netty-server-sync:1.11.9
//> using dep ch.qos.logback:logback-classic:1.5.8

package sttp.tapir.examples.custom_types

import sttp.tapir.*
import sttp.tapir.server.netty.sync.NettySyncServer

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")

@main def enumQueryParameter(): Unit =
given Codec[String, PieType, CodecFormat.TextPlain] =
Codec.derivedEnumeration[String, PieType](decode = s => PieType.values.find(_.name == s), encode = _.name)

val bake = endpoint.get
.in("bake")
.in(query[PieType]("pie"))
.out(stringBody)
.handleSuccess(pie => s"Baking: $pie!")

NettySyncServer().addEndpoint(bake).startAndWait()
Loading