猿问

通过注释向 graphQL java 添加自定义验证

从网上的博客我明白了。


默认情况下,将从 Java 类型推断标准 GraphQL 类型(String、Integer、Long、Float、Boolean、Enum、List)。此外,它还会尊重@javax.validation.constraints.NotNull关于值的可为空性的注释,以及@GraphQLNonNull


我正在尝试一个@UUID可以验证的注释


@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;


}

当我尝试添加带有突变的帖子时,注释不起作用。请帮忙解决这个问题。


饮歌长啸
浏览 93回答 1
1回答

吃鸡游戏

这里没有解析器,所以我不确定你是如何创建的,MutationResolver所以我将举一个例子并希望它有所帮助。重要的是你需要有@Validated注释@Valid。所以就我而言:架构:schema {&nbsp; &nbsp; query: Query&nbsp; &nbsp; mutation: Mutation}type Vehicle {&nbsp; &nbsp; id: ID!&nbsp; &nbsp; name: String}input VehicleInput {&nbsp; &nbsp; name: String&nbsp; &nbsp; type: String}type Mutation {&nbsp; &nbsp; addVehicle(vehicle: VehicleInput): Vehicle}解决:@Validated@Component@RequiredArgsConstructorpublic class VehicleMutationResolver implements GraphQLMutationResolver {&nbsp; &nbsp; public Vehicle addVehicle(@Valid VehicleInput input) {&nbsp; &nbsp; &nbsp; &nbsp; return new Vehicle(UUID.randomUUID().toString(), input.getName());&nbsp; &nbsp; }}和输入对象:@Data@ToStringpublic class VehicleInput {&nbsp; &nbsp; private String type;&nbsp; &nbsp; @Size(min = 3)&nbsp; &nbsp; private String name;}因此,如果您提供小于 3 的字符串,您将收到错误addVehicle.input.name: size must be between 3 and 2147483647如果这没有帮助,请提供更多数据。
随时随地看视频慕课网APP

相关分类

Java
我要回答