Search code examples
javagraphqlgraphql-java

Add custom validation via annotation to graphQL java


From the blogs online I understood.

By default, standard GraphQL types (String, Integer, Long, Float, Boolean, Enum, List) will be inferred from Java types. Also, it will respect @javax.validation.constraints.NotNull annotation with respect to value's nullability, as well as @GraphQLNonNull

I am trying for an annotation @UUID which could validate

@Target(ElementType.FIELD)
@Constraint(validatedBy={})
@Retention(RUNTIME)
@Pattern(regexp="^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
public @interface UUID {
    String message() default "{invalid.uuid}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
public class Post {

    public Post() {
    }

    private String id;
    private String title;
    @UUID
    private String category;
    private Author author;

}

The annotation is not working while I am trying to add a post with the mutation. Please help with this.


Solution

  • There is no resolver here so I'm not sure how you create MutationResolver so I will put mu example and hope it helps.

    Important is that you need to have @Validated and @Valid annotations.

    So in my case: Schema:

    schema {
        query: Query
        mutation: Mutation
    }
    
    
    type Vehicle {
        id: ID!
        name: String
    }
    
    input VehicleInput {
        name: String
        type: String
    }
    
    type Mutation {
        addVehicle(vehicle: VehicleInput): Vehicle
    }
    

    Resolver:

    @Validated
    @Component
    @RequiredArgsConstructor
    public class VehicleMutationResolver implements GraphQLMutationResolver {
    
        public Vehicle addVehicle(@Valid VehicleInput input) {
            return new Vehicle(UUID.randomUUID().toString(), input.getName());
        }
    }
    

    And input object:

    @Data
    @ToString
    public class VehicleInput {
    
        private String type;
    
        @Size(min = 3)
        private String name;
    }
    

    So if you provide string that is smaller than 3 you will get error addVehicle.input.name: size must be between 3 and 2147483647

    If this doesn't help please provide more data.