Skip to content

Commit

Permalink
Schema.Primitive respects default annotation for defaultValue (#715)
Browse files Browse the repository at this point in the history
Add Schema.defaultValue to set default of a schema
  • Loading branch information
987Nabil committed Aug 30, 2024
1 parent ce8cca1 commit e7b2559
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ object DefaultValueSpec extends ZIOSpecDefault {
val rightSchema = Schema.either(Schema.fail("Nothing"), Schema.primitive(StandardType.StringType))
assert(rightSchema.defaultValue)(isRight(isRight(equalTo(""))))
}
)
),
suite("default from annotation") {
test("default value from annotation") {
assert(Schema[String].defaultValue("default").defaultValue)(isRight(equalTo("default")))
}
}
)
}
15 changes: 14 additions & 1 deletion zio-schema/shared/src/main/scala/zio/schema/Schema.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ sealed trait Schema[A] {
*/
def defaultValue: scala.util.Either[String, A]

/**
* Add a default value to this schema.
*/
def defaultValue(value: A): Schema[A] = self.annotate(fieldDefaultValue(value))

/**
* Chunk of annotations for this schema
*/
Expand Down Expand Up @@ -562,7 +567,15 @@ object Schema extends SchemaPlatformSpecific with SchemaEquality {

override def annotate(annotation: Any): Primitive[A] = copy(annotations = (annotations :+ annotation).distinct)

override def defaultValue: scala.util.Either[String, A] = standardType.defaultValue
private def annotatedDefaultValue = annotations.collectFirst {
case a if a.isInstanceOf[fieldDefaultValue[_]] => a.asInstanceOf[fieldDefaultValue[A]].value
}

override def defaultValue: scala.util.Either[String, A] =
annotatedDefaultValue match {
case Some(value) => Right(value)
case None => standardType.defaultValue
}

override def makeAccessors(b: AccessorBuilder): Unit = ()
}
Expand Down

0 comments on commit e7b2559

Please sign in to comment.