diff --git a/codegen/src/main/scala/caliban/codegen/ClientWriter.scala b/codegen/src/main/scala/caliban/codegen/ClientWriter.scala index e639639bc..978ba0ea8 100644 --- a/codegen/src/main/scala/caliban/codegen/ClientWriter.scala +++ b/codegen/src/main/scala/caliban/codegen/ClientWriter.scala @@ -249,9 +249,8 @@ object ClientWriter { ) } val args = field.args match { - case Nil => "" - case list => - s"(${list.map(arg => s"${safeName(arg.name)}: ${writeType(arg.ofType)}").mkString(", ")})" + case Nil => "" + case list => s"(${writeArgumentFields(list)})" } val argBuilder = field.args match { case Nil => "" @@ -263,7 +262,7 @@ object ClientWriter { } def writeArgumentFields(args: List[InputValueDefinition]): String = - s"${args.map(arg => s"${safeName(arg.name)}: ${writeType(arg.ofType)}").mkString(", ")}" + s"${args.map(arg => s"${safeName(arg.name)}: ${writeType(arg.ofType)}${if (arg.ofType.nullable) " = None" else ""}").mkString(", ")}" def writeArguments(field: FieldDefinition): String = if (field.args.nonEmpty) { diff --git a/codegen/src/test/scala/caliban/codegen/ClientWriterSpec.scala b/codegen/src/test/scala/caliban/codegen/ClientWriterSpec.scala index ccb70c56e..302045f43 100644 --- a/codegen/src/test/scala/caliban/codegen/ClientWriterSpec.scala +++ b/codegen/src/test/scala/caliban/codegen/ClientWriterSpec.scala @@ -356,6 +356,37 @@ object Client { def nicknames: SelectionBuilder[Character, List[String]] = Field("nicknames", ListOf(Scalar())) } +} +""" + ) + ) + }, + testM("default to None for optional arguments") { + val schema = + """ + type Query { + characters( + first: Int! + last: Int + ): String + }""".stripMargin + + assertM( + gen(schema), + equalTo( + """import caliban.client.FieldBuilder._ +import caliban.client.SelectionBuilder._ +import caliban.client._ +import caliban.client.Operations._ + +object Client { + + type Query = RootQuery + object Query { + def characters(first: Int, last: Option[Int] = None): SelectionBuilder[RootQuery, Option[String]] = + Field("characters", OptionOf(Scalar()), arguments = List(Argument("first", first), Argument("last", last))) + } + } """ ) diff --git a/core/src/main/scala/caliban/parsing/adt/Type.scala b/core/src/main/scala/caliban/parsing/adt/Type.scala index 369ea7a76..f30f663fb 100644 --- a/core/src/main/scala/caliban/parsing/adt/Type.scala +++ b/core/src/main/scala/caliban/parsing/adt/Type.scala @@ -2,7 +2,10 @@ package caliban.parsing.adt import scala.annotation.tailrec -sealed trait Type +sealed trait Type { + val nonNull: Boolean + var nullable: Boolean = !nonNull +} object Type {