Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make fraction part in DigitsConstraint optional #92

Merged
merged 4 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ The element must be a number inside the specified `integer` and `fraction` range

- Applies to : `String`, `Byte`, `Short`, `Int`, `Long`, `BigDecimal`, `BigInteger`, `Float`, `Lists`

- SDL : `directive @Digits(integer : Int!, fraction : Int!, message : String = "graphql.validation.Digits.message") on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION`
- SDL : `directive @Digits(integer : Int!, fraction : Int, message : String = "graphql.validation.Digits.message") on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION`

- Message : `graphql.validation.Digits.message`

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static graphql.schema.GraphQLTypeUtil.isList;
import static graphql.validation.rules.ValidationEnvironment.ValidatedElement.FIELD;
Expand Down Expand Up @@ -198,23 +199,28 @@ protected boolean isOneOfTheseTypes(GraphQLInputType inputType, Collection<Graph
}

/**
* Returns an integer argument from a directive (or its default) and throws an assertion of the argument is null
* Returns an integer argument from a directive (or its default) and throws an assertion if the argument is null
*
* @param directive the directive to check
* @param argName the argument name
* @return a non null value
*/
protected int getIntArg(GraphQLAppliedDirective directive, String argName) {
GraphQLAppliedDirectiveArgument argument = directive.getArgument(argName);
if (argument == null) {
return assertExpectedArgType(argName, "Int");
}
return getIntArgOpt(directive, argName)
.orElseGet(() -> assertExpectedArgType(argName, "Int"));
}

Number value = argument.getValue();
if (value == null) {
return assertExpectedArgType(argName, "Int");
}
return value.intValue();
/**
* Returns an optional integer argument from a directive (or its default), or empty Optional if the argument is null.
*
* @param directive the directive to check
* @param argName the argument name
* @return an optional null value
*/
protected Optional<Integer> getIntArgOpt(GraphQLAppliedDirective directive, String argName) {
return Optional.ofNullable(directive.getArgument(argName))
.map(GraphQLAppliedDirectiveArgument::<Number>getValue)
.map(Number::intValue);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static graphql.validation.constraints.GraphQLScalars.GRAPHQL_NUMBER_AND_STRING_TYPES;

Expand All @@ -21,14 +22,14 @@ public DigitsConstraint() {
@Override
public Documentation getDocumentation() {
return Documentation.newDocumentation()
.messageTemplate(getMessageTemplate())
.description("The element must be a number inside the specified `integer` and `fraction` range.")
.example("buyCar( carCost : Float @Digits(integer : 5, fraction : 2) : DriverDetails")
.applicableTypes(GRAPHQL_NUMBER_AND_STRING_TYPES)
.directiveSDL("directive @Digits(integer : Int!, fraction : Int!, message : String = \"%s\") " +
"on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION",
getMessageTemplate())
.build();
.messageTemplate(getMessageTemplate())
.description("The element must be a number inside the specified `integer` and optionally inside `fraction` range.")
.example("buyCar( carCost : Float @Digits(integer : 5, fraction : 2) : DriverDetails")
.applicableTypes(GRAPHQL_NUMBER_AND_STRING_TYPES)
.directiveSDL("directive @Digits(integer : Int!, fraction : Int, message : String = \"%s\") " +
"on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION",
getMessageTemplate())
.build();
}

@Override
Expand All @@ -43,28 +44,40 @@ protected List<GraphQLError> runConstraint(ValidationEnvironment validationEnvir

GraphQLAppliedDirective directive = validationEnvironment.getContextObject(GraphQLAppliedDirective.class);
int maxIntegerLength = getIntArg(directive, "integer");
int maxFractionLength = getIntArg(directive, "fraction");
Optional<Integer> maxFractionLengthOpt = getIntArgOpt(directive, "fraction");

boolean isOk;
try {
BigDecimal bigNum = asBigDecimal(validatedValue);
isOk = isOk(bigNum, maxIntegerLength, maxFractionLength);
boolean isFractionPartOk = maxFractionLengthOpt
.map(maxFractionLength -> isFractionPartOk(bigNum, maxFractionLength))
.orElse(true);

isOk = isFractionPartOk && isIntegerPartOk(bigNum, maxIntegerLength);
} catch (NumberFormatException e) {
isOk = false;
}

if (!isOk) {
return mkError(validationEnvironment, "integer", maxIntegerLength, "fraction", maxFractionLength);
return mkError(
validationEnvironment,
"integer",
maxIntegerLength, "fraction",
maxFractionLengthOpt.map(Object::toString).orElse("unlimited")
);
}

return Collections.emptyList();
}

private boolean isOk(BigDecimal bigNum, int maxIntegerLength, int maxFractionLength) {
int integerPartLength = bigNum.precision() - bigNum.scale();
int fractionPartLength = Math.max(bigNum.scale(), 0);
private static boolean isIntegerPartOk(BigDecimal bigNum, int maxIntegerLength) {
final int integerPartLength = bigNum.precision() - bigNum.scale();
return maxIntegerLength >= integerPartLength;
}

return maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength;
private static boolean isFractionPartOk(BigDecimal bigNum, int maxFractionLength) {
final int fractionPartLength = Math.max(bigNum.scale(), 0);
return maxFractionLength >= fractionPartLength;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class DigitsConstraintTest extends BaseConstraintTestSupport {
'field( arg : String @Digits(integer : 5, fraction : 2) ) : ID' | null | ''
'field( arg : String @Digits(integer : 5, fraction : 2) ) : ID' | Byte.valueOf("0") | ''
'field( arg : String @Digits(integer : 5, fraction : 2) ) : ID' | Double.valueOf("500.2") | ''
'field( arg : String @Digits(integer : 5) ) : ID' | Double.valueOf("500.2345678") | ''

'field( arg : String @Digits(integer : 5, fraction : 2) ) : ID' | new BigDecimal("-12345.12") | ''
'field( arg : String @Digits(integer : 5, fraction : 2) ) : ID' | new BigDecimal("-123456.12") | 'Digits;path=/arg;val:-123456.12;\t'
Expand Down