javagraphqlgraphql-javagraphql-spqr

Model NaN in a Double value in graphql-spqr


There is no standard to represent NaN and INFINITY in neither the Graphql and also in JSON.

In JavaScript, JSON.stringify(0/0) and JSON.stringify(1/0) will just return string null.

It cause little trouble when I am providing GraphQL endpoint with Java backed. My value could be any valid Double in Java.

    @GraphQLQuery
    private Double precentage;

I have few workarounds and I could patch it in a setter which I am doing. Just wonder if there is a de-facto standards to handle it in a nicer way.


Solution

  • I was thinking about this at some point as well... The current situation is that Double (the Java type) gets mapped to GraphQL Float scalar, which by design can not represent NaN or ±Infinity. What you could do is implement your own scalar (called e.g. Double) and decide on how you will deal with the these special cases (use the existing scalar implementations as a guideline). Perhaps use strings like NaN, +Infinity, -Infinity? The worst part is whatever convention you settle on, the client needs to be aware of it too, as JSON has no representation for these values either.

    Once you have a custom scalar you're happy with, you can implement a super simple TypeMapper that supports Double (the Java type) and returns this new scalar.

    Or to answer your original question - no, unfortunately there's nothing out of the box yet in either graphql-java or SPQR. But I'm happy to extend SPQR's custom scalars to deal wiht this... If you come up with a good strategy, do ping me.