11package graphql .validation .directives .standardrules ;
22
3- import graphql .Assert ;
43import graphql .GraphQLError ;
54import graphql .Scalars ;
65import graphql .schema .GraphQLDirective ;
@@ -28,6 +27,7 @@ public String getDirectiveDeclarationSDL() {
2827 @ Override
2928 public boolean appliesToType (GraphQLInputType inputType ) {
3029 return isOneOfTheseTypes (inputType ,
30+ Scalars .GraphQLString ,
3131 Scalars .GraphQLByte ,
3232 Scalars .GraphQLShort ,
3333 Scalars .GraphQLInt ,
@@ -42,33 +42,35 @@ public boolean appliesToType(GraphQLInputType inputType) {
4242 @ Override
4343 public List <GraphQLError > runValidation (ValidationRuleEnvironment ruleEnvironment ) {
4444 Object argumentValue = ruleEnvironment .getFieldOrArgumentValue ();
45+ if (argumentValue == null ) {
46+ return Collections .emptyList ();
47+ }
4548
4649 GraphQLDirective directive = ruleEnvironment .getContextObject (GraphQLDirective .class );
4750 int maxIntegerLength = getIntArg (directive , "integer" );
4851 int maxFractionLength = getIntArg (directive , "fraction" );
4952
50- if (argumentValue == null ) {
51- return Collections .emptyList ();
52- }
53-
54- BigDecimal bigNum ;
55- if (argumentValue instanceof BigDecimal ) {
56- bigNum = (BigDecimal ) argumentValue ;
57- } else if (argumentValue instanceof Number ) {
58- bigNum = new BigDecimal (argumentValue .toString ()).stripTrailingZeros ();
59- } else {
60- return Assert .assertShouldNeverHappen ("You MUST provide a Number of the Digits directive rule" );
53+ boolean isOk ;
54+ try {
55+ BigDecimal bigNum = asBigDecimal (argumentValue );
56+ isOk = isOk (bigNum , maxIntegerLength , maxFractionLength );
57+ } catch (NumberFormatException e ) {
58+ isOk = false ;
6159 }
6260
63- int integerPartLength = bigNum .precision () - bigNum .scale ();
64- int fractionPartLength = bigNum .scale () < 0 ? 0 : bigNum .scale ();
65-
66- if (!(maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength )) {
61+ if (!isOk ) {
6762 return mkError (ruleEnvironment , directive , mkMessageParams (
6863 "integer" , maxIntegerLength ,
69- "fraction" , fractionPartLength ,
64+ "fraction" , maxFractionLength ,
7065 "fieldOrArgumentValue" , argumentValue ));
7166 }
7267 return Collections .emptyList ();
7368 }
69+
70+ private boolean isOk (BigDecimal bigNum , int maxIntegerLength , int maxFractionLength ) {
71+ int integerPartLength = bigNum .precision () - bigNum .scale ();
72+ int fractionPartLength = bigNum .scale () < 0 ? 0 : bigNum .scale ();
73+
74+ return maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength ;
75+ }
7476}
0 commit comments