Skip to content

Commit

Permalink
Use a ListBuffer in toResponseValue
Browse files Browse the repository at this point in the history
  • Loading branch information
kyri-petrou committed Jun 17, 2024
1 parent 8040c6f commit ae0cad9
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions core/src/main/scala/caliban/GraphQLResponse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import caliban.interop.play.{ IsPlayJsonReads, IsPlayJsonWrites }
import caliban.interop.tapir.IsTapirSchema
import caliban.interop.zio.{ IsZIOJsonCodec, IsZIOJsonDecoder, IsZIOJsonEncoder }

import scala.collection.mutable.ListBuffer

/**
* Represents the result of a GraphQL query, containing a data object and a list of errors.
*/
Expand All @@ -19,28 +21,33 @@ case class GraphQLResponse[+E](
) {
def toResponseValue: ResponseValue = toResponseValue(keepDataOnErrors = true)

def toResponseValue(keepDataOnErrors: Boolean, excludeExtensions: Option[Set[String]] = None): ResponseValue =
if (errors.isEmpty && extensions.isEmpty && hasNext.isEmpty) {
ObjectValue(("data", data) :: Nil)
} else {
val hasErrors = errors.nonEmpty
ObjectValue(
List(
"data" -> (if (!hasErrors || keepDataOnErrors) Some(data) else None),
"errors" -> (if (hasErrors)
Some(ListValue(errors.map {
case e: CalibanError => e.toResponseValue
case e => ObjectValue(List("message" -> StringValue(e.toString)))
}))
else None),
"extensions" -> excludeExtensions.fold(extensions)(excl =>
extensions.map(obj => ObjectValue(obj.fields.filterNot(f => excl.contains(f._1))))
),
"hasNext" -> hasNext.map(BooleanValue.apply)
).collect { case (name, Some(v)) => name -> v }
)
def toResponseValue(keepDataOnErrors: Boolean, excludeExtensions: Option[Set[String]] = None): ResponseValue = {
val builder = new ListBuffer[(String, ResponseValue)]
val hasErrors = errors.nonEmpty
val extensions0 = excludeExtensions match {
case None => extensions
case Some(excl) =>
extensions.flatMap { obj =>
val newFields = obj.fields.filterNot(f => excl.contains(f._1))
if (newFields.nonEmpty) Some(ObjectValue(newFields)) else None
}
}

if (!hasErrors || keepDataOnErrors)
builder += "data" -> data
if (hasErrors)
builder += "errors" -> ListValue(errors.map {
case e: CalibanError => e.toResponseValue
case e => ObjectValue(List("message" -> StringValue(e.toString)))
})
if (extensions0.nonEmpty)
builder += "extensions" -> extensions0.get
if (hasNext.nonEmpty)
builder += "hasNext" -> BooleanValue(hasNext.get)

ObjectValue(builder.result())
}

def withExtension(key: String, value: ResponseValue): GraphQLResponse[E] =
copy(extensions = Some(ObjectValue(extensions.foldLeft(List(key -> value)) { case (value, ObjectValue(fields)) =>
value ::: fields
Expand Down

0 comments on commit ae0cad9

Please sign in to comment.