1
1
package graphql .validation .directives .standardrules ;
2
2
3
- import graphql .Assert ;
4
3
import graphql .GraphQLError ;
5
4
import graphql .Scalars ;
6
5
import graphql .schema .GraphQLDirective ;
@@ -28,6 +27,7 @@ public String getDirectiveDeclarationSDL() {
28
27
@ Override
29
28
public boolean appliesToType (GraphQLInputType inputType ) {
30
29
return isOneOfTheseTypes (inputType ,
30
+ Scalars .GraphQLString ,
31
31
Scalars .GraphQLByte ,
32
32
Scalars .GraphQLShort ,
33
33
Scalars .GraphQLInt ,
@@ -42,33 +42,35 @@ public boolean appliesToType(GraphQLInputType inputType) {
42
42
@ Override
43
43
public List <GraphQLError > runValidation (ValidationRuleEnvironment ruleEnvironment ) {
44
44
Object argumentValue = ruleEnvironment .getFieldOrArgumentValue ();
45
+ if (argumentValue == null ) {
46
+ return Collections .emptyList ();
47
+ }
45
48
46
49
GraphQLDirective directive = ruleEnvironment .getContextObject (GraphQLDirective .class );
47
50
int maxIntegerLength = getIntArg (directive , "integer" );
48
51
int maxFractionLength = getIntArg (directive , "fraction" );
49
52
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 ;
61
59
}
62
60
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 ) {
67
62
return mkError (ruleEnvironment , directive , mkMessageParams (
68
63
"integer" , maxIntegerLength ,
69
- "fraction" , fractionPartLength ,
64
+ "fraction" , maxFractionLength ,
70
65
"fieldOrArgumentValue" , argumentValue ));
71
66
}
72
67
return Collections .emptyList ();
73
68
}
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
+ }
74
76
}
0 commit comments