Skip to content

Commit

Permalink
Use correct validator when creating an enum codec so that error messa…
Browse files Browse the repository at this point in the history
…ges are rendered correctly (#4175)
  • Loading branch information
adamw authored Nov 18, 2024
1 parent 51e6df4 commit 796e328
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
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()

0 comments on commit 796e328

Please sign in to comment.