Skip to content

Commit

Permalink
Scala3 support for non discriminator play json union (#702)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbryzek authored Jul 3, 2024
1 parent 3ebda99 commit c383db9
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion scala-generator/src/main/scala/models/Play2Json.scala
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,34 @@ case class Play2Json(
}

private def readersWithoutDiscriminator(union: ScalaUnion): String = {
if (scala3Support) {
readersWithoutDiscriminatorScala3(union)
} else {
readersWithoutDiscriminatorScala2(union)
}
}

private def readersWithoutDiscriminatorScala3(union: ScalaUnion): String = {
union.types.toList match {
case Nil => {
s"${play2JsonCommon.implicitUnionReader(union)} = (json: play.api.libs.json.JsValue) => play.api.libs.json.JsError(\"Union has no declared types\")"
}
case first :: rest => {
val types = (Seq("default") ++ rest.map { scalaUnionType =>
s"${readerUnqualified(union, scalaUnionType)}.reads(json).map(_.asInstanceOf[T])"
}).mkString("Seq(\n ", ",\n ", "\n )")
s"""
|${play2JsonCommon.implicitUnionReader(union)} = (json: play.api.libs.json.JsValue) => {
| val default = ${readerUnqualified(union, first)}.reads(json).map(_.asInstanceOf[T])
| val all: Seq[play.api.libs.json.JsResult[T]] = $types
| all.view.find(_.isSuccess).getOrElse(default)
|}
|""".stripMargin
}
}
}

private def readersWithoutDiscriminatorScala2(union: ScalaUnion): String = {
Seq(
s"${play2JsonCommon.implicitUnionReader(union)} = {",
s" (",
Expand Down Expand Up @@ -263,7 +291,6 @@ case class Play2Json(
Seq(
"discriminator match {",
unionTypesWithNames(union).map { t =>
// OLD: Pre scala3: s"""case "${t.unionType.discriminatorName}" => js.validate[${t.typeName}]"""
s"""case "${t.unionType.discriminatorName}" => ${play2JsonCommon.implicitReaderNameQualified(ssd.namespaces, t.unionType.name)}.reads(js)"""
}.mkString("\n").indentString(2),
s"""case other => play.api.libs.json.JsSuccess(${union.undefinedType.datatype.fullName}(other))""".indentString(2),
Expand Down

0 comments on commit c383db9

Please sign in to comment.