Skip to content

Commit

Permalink
use field.getUnlessDefault instead of field.get in UrlFormDataEncoder
Browse files Browse the repository at this point in the history
  • Loading branch information
bpholt committed Jan 2, 2024
1 parent 1488301 commit 188e8ad
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,75 @@ object UrlFormDataEncoderDecoderSchemaVisitorSpec extends SimpleIOSuite {
)
}

pureTest("struct: default (but not required) values are omitted from encoded output") {
val defaultValue = "default"
case class Foo(x: Int, y: String)
object Foo {
implicit val schema: Schema[Foo] = {
val x = int.required[Foo]("x", _.x)
val y = smithy4s.schema.Field[Foo, String]("x", string, _.y).addHints(smithy.api.Default(smithy4s.Document.fromString(defaultValue)))
struct(x, y)(Foo.apply)
}
}

expect.same(
UrlForm
.Encoder(
capitalizeStructAndUnionMemberNames = false
)
.fromSchema(Foo.schema)
.encode(Foo(42, defaultValue))
.render,
"x=42"
)
}

pureTest("struct: required default values are included in encoded output") {
val defaultValue = "default"
case class Foo(x: Int, y: String)
object Foo {
implicit val schema: Schema[Foo] = {
val x = int.required[Foo]("x", _.x)
val y = string.required[Foo]("y", _.y).addHints(smithy.api.Default(smithy4s.Document.fromString(defaultValue)))
struct(x, y)(Foo.apply)
}
}

expect.same(
UrlForm
.Encoder(
capitalizeStructAndUnionMemberNames = false
)
.fromSchema(Foo.schema)
.encode(Foo(42, defaultValue))
.render,
"x=42&y=default"
)
}

pureTest("struct: optional default values are omitted from encoded output") {
val defaultValue = "default"
case class Foo(x: Int, y: Option[String])
object Foo {
implicit val schema: Schema[Foo] = {
val x = int.required[Foo]("x", _.x)
val y = string.optional[Foo]("y", _.y).addHints(smithy.api.Default(smithy4s.Document.fromString(defaultValue)))
struct(x, y)(Foo.apply)
}
}

expect.same(
UrlForm
.Encoder(
capitalizeStructAndUnionMemberNames = false
)
.fromSchema(Foo.schema)
.encode(Foo(42, Some(defaultValue)))
.render,
"x=42"
)
}

pureTest("list") {
case class Foo(foos: List[Int])
object Foo {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,14 @@ private[http] class UrlFormDataEncoderSchemaVisitor(
make: IndexedSeq[Any] => S
): UrlFormDataEncoder[S] = {
def fieldEncoder[A](field: Field[S, A]): UrlFormDataEncoder[S] =
compile(field.schema)
.contramap(field.get)
new UrlFormDataEncoder[S] {
private lazy val cachedEncoder = compile(field.schema)
override def encode(value: S): List[UrlForm.FormData] =
field
.getUnlessDefault(value)
.toList
.flatMap(cachedEncoder.encode)
}
.prepend(getKey(field.hints, field.label))
val encoders = fields.map(fieldEncoder(_))
struct => encoders.toList.flatMap(_.encode(struct))
Expand Down

0 comments on commit 188e8ad

Please sign in to comment.