Skip to content

Commit

Permalink
Default to None in client for optional arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
kitlangton committed Feb 29, 2020
1 parent a916ad6 commit f3f3898
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
7 changes: 3 additions & 4 deletions codegen/src/main/scala/caliban/codegen/ClientWriter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 => ""
Expand All @@ -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) {
Expand Down
31 changes: 31 additions & 0 deletions codegen/src/test/scala/caliban/codegen/ClientWriterSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
}
"""
)
Expand Down
5 changes: 4 additions & 1 deletion core/src/main/scala/caliban/parsing/adt/Type.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down

0 comments on commit f3f3898

Please sign in to comment.