在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):graphql-java/graphql-java-extended-validation开源软件地址(OpenSource Url):https://github.com/graphql-java/graphql-java-extended-validation开源编程语言(OpenSource Language):Java 64.4%开源软件介绍(OpenSource Introduction):Extended Validation for graphql-javaThis library provides extended validation of fields and field arguments for graphql-java Using<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-extended-validation</artifactId>
<version>18.1</version>
</dependency> compile 'com.graphql-java:graphql-java-extended-validation:18.1'
It's currently available from Maven central. SDL @Directive constraintsThis library provides a series of directives that can be applied to field arguments and input type fields which will constrain their allowable values. These names and semantics are inspired from the javax.validation annotations https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/package-summary.html You can add these onto arguments or input types in your graphql SDL. For example #
# this declares the directive as being possible on arguments and input fields
#
directive @Size(min : Int = 0, max : Int = 2147483647, message : String = "graphql.validation.Size.message")
on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
input Application {
name : String @Size(min : 3, max : 100)
}
type Query {
hired (applications : [Application!] @Size(max : 10)) : [Boolean]
} In the example above, we have a Java Expression Language (Java EL)The Java EL is a powerful expression syntax for expressing validation conditions. Some simple sample Java EL expressions might be :
The following validation variables are made available to you :
The Java EL expression MUST evaluate to a boolean value to be useful in the See here for a more complete overview of Java EL Message InterpolationThe validation code uses a You can use Java EL syntax in the message templates to format even more powerful error messages.
If you use directive arguments like Like javax.validation, this library ships with some default error message templates but you can override them. I18n Locale SupportThe validation library aims to offer Internationalisation (18N) of the error messages. When the validation rules
run they are passed in a A In the mean time you can work around this by having the Schema Directive WiringIf you are using graphql SDL to build your graphql schema then you can use a This allows you to automatically enhance your schema with validation by directives alone. The following shows how to setup the SDL generation so that the build schema will have validation in place. //
// This contains by default the standard library provided @Directive constraints
//
ValidationRules validationRules = ValidationRules.newValidationRules()
.onValidationErrorStrategy(OnValidationErrorStrategy.RETURN_NULL)
.build();
//
// This will rewrite your data fetchers when rules apply to them so that validation
ValidationSchemaWiring schemaWiring = new ValidationSchemaWiring(validationRules);
//
// we add this schema wiring to the graphql runtime
RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring().directiveWiring(schemaWiring).build();
//
// then pretty much standard graphql-java code to build a graphql schema
Reader sdl = buildSDL();
TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(sdl);
GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefinitionRegistry, runtimeWiring); Under the covers If they do apply then it rewrites the DataFetcher so that it first calls the validation code and produces errors if the field input is not considered valid. The default strategy Using the API direct in your own data fetchersWe recommend that you use the SDL schema directive wiring and @directives for the easiest way to get input type validation. However there can be reasons why you cant use this approach and you have use the API directly in your data fetching code.
//
// an example of writing your own custom validation rule
//
ValidationRule myCustomValidationRule = new ValidationRule() {
@Override
public boolean appliesTo(GraphQLFieldDefinition fieldDefinition, GraphQLFieldsContainer fieldsContainer) {
return fieldDefinition.getName().equals("decide whether this rule applies here");
}
@Override
public boolean appliesTo(GraphQLArgument argument, GraphQLFieldDefinition fieldDefinition, GraphQLFieldsContainer fieldsContainer) {
return argument.getName().equals("decide whether this rule applies here to an argument");
}
@Override
public List<GraphQLError> runValidation(ValidationEnvironment validationEnvironment) {
List<GraphQLError> errors = new ArrayList<>();
Map<String, Object> argumentValues = validationEnvironment.getArgumentValues();
for (String argName : argumentValues.keySet()) {
Object argValue = argumentValues.get(argName);
GraphQLError error = runCodeThatValidatesInputHere(validationEnvironment, argName, argValue);
if (error != null) {
errors.add(error);
}
}
return errors;
}
};
DataFetcher dataFetcher = new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment env) {
//
// By default the ValidationRule contains the SDL @directive rules, but
// you can also add your own as we do here.
//
ValidationRules validationRules = ValidationRules
.newValidationRules()
.locale(Locale.getDefault())
.addRule(myCustomValidationRule)
.build();
//
// The expected strategy is to return null data and the errors if there are any validation
// problems
//
List<GraphQLError> errors = validationRules.runValidationRules(env);
if (!errors.isEmpty()) {
return DataFetcherResult.newResult().errors(errors).data(null).build();
}
return normalDataFetchingCodeRunsNow(env);
}
}; The above code shows a custom validation rule (with nonsense logic for demonstration purposes) and then a data fetcher
that uses the The supplied @Directive constraints@AssertFalseThe boolean value must be false.
@AssertTrueThe boolean value must be true.
@DecimalMaxThe element must be a number whose value must be less than or equal to the specified maximum.
@DecimalMinThe element must be a number whose value must be greater than or equal to the specified minimum.
@DigitsThe element must be a number inside the specified
@ExpressionThe provided expression must evaluate to true. The expression language is Java EL and expressions MUST resolve to a boolean value, ie. it is valid or not.
@MaxThe element must be a number whose value must be less than or equal to the specified maximum.
@MinThe element must be a number whose value must be greater than or equal to the specified minimum.
@NegativeThe element must be a negative number.
@NegativeOrZeroThe element must be a negative number or zero.
@NotBlankThe String must contain at least one non-whitespace character, according to Java's Character.isWhitespace().
@NotEmptyThe element must have a non-zero size.
@ContainerNotEmptyThe list or input object must have a non-zero size.
@PatternThe String must match the specified regular expression, which follows the Java regular expression conventions.
@PositiveThe element must be a positive number.
@PositiveOrZeroThe element must be a positive number or zero.
@RangeThe element range must be between the specified
@SizeThe string's size must be between the specified
@ContainerSizeThe list's or input object's size must be between the specified
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论