Skip to content

Commit

Permalink
Merge pull request #167 from sangria-graphql/double-output-validation
Browse files Browse the repository at this point in the history
Validate output double values
  • Loading branch information
OlegIlyenko authored Oct 13, 2016
2 parents c11f02f + 41f8fc0 commit 1b37654
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package sangria.schema

case class OutputValueCoercionException(message: String) extends Exception(message)
10 changes: 9 additions & 1 deletion src/main/scala/sangria/schema/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,15 @@ package object schema {
description = Some(
"The `Float` scalar type represents signed double-precision fractional " +
"values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)."),
coerceOutput = valueOutput,
coerceOutput = (v, _) {
// .isNaN and .isInfinity box, we explicitly avoid that here
if (java.lang.Double.isNaN(v))
throw OutputValueCoercionException("Double value is NaN")
else if (java.lang.Double.isInfinite(v))
throw OutputValueCoercionException("Double value is infinite")
else
v
},
coerceUserInput = {
case i: Int Right(i.toDouble)
case i: Long Right(i.toDouble)
Expand Down
13 changes: 13 additions & 0 deletions src/test/scala/sangria/schema/CoercionSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ class CoercionSpec extends WordSpec with Matchers {
FloatType.coerceOutput(123.456, Set.empty) should be (123.456)
}

"Float is not allowed to be Nan" in {
an [OutputValueCoercionException] should be thrownBy
FloatType.coerceOutput(Double.NaN, Set.empty)
}

"Float is not allowed to be infinity" in {
an [OutputValueCoercionException] should be thrownBy
FloatType.coerceOutput(Double.PositiveInfinity, Set.empty)

an [OutputValueCoercionException] should be thrownBy
FloatType.coerceOutput(Double.NegativeInfinity, Set.empty)
}

"BigDecimal" in {
BigDecimalType.coerceOutput(BigDecimal("467356453726547623.37467823648763238479823"), Set.empty) should be (
BigDecimal("467356453726547623.37467823648763238479823"))
Expand Down

0 comments on commit 1b37654

Please sign in to comment.