简体   繁体   English

GraphQL java spring 引导插件无法识别自定义标量日期

[英]Custom scalar Date not recognized by GraphQL java spring boot plugin for unit test

I wrote this unit test for my controller and my schema contains a Date object which is implemented by the DateScalarConfiguration below.我为我的 controller 编写了这个单元测试,我的模式包含一个 Date object,它由下面的 DateScalarConfiguration 实现。 When I run the application there is no problems but when I'm testing it it gives me an error.当我运行应用程序时没有问题,但是当我测试它时它给了我一个错误。 This my code:这是我的代码:

@GraphQlTest(MyController.class)
@Import(DateScalarConfiguration.class)

   .....

   @Test
    public void findMyObjectTest() {
        List<String> fileExtensions = Arrays.asList(".graphql", ".gql", ".graphqls");
        DocumentSource documentSource = new ResourceDocumentSource(
                Collections.singletonList(new ClassPathResource("graphql/")),
                fileExtensions); // ResourceDocumentSource.FILE_EXTENSIONS
        this.graphQlTester
                .mutate()
                .documentSource(documentSource)
                .build().documentName("schema")
                .variable("myVar",618)
                .execute()
                .path("findMyObject")
                .matchesJson("{\"data\":{\"findMyObject\":{\"ATTR1\":618,\"ATTR2\":\"1999-12-31\"}}}");
    }

DateScalarConfiguration:日期标量配置:

@Configuration
public class DateScalarConfiguration  {

    @Bean
    public GraphQLScalarType dateScalar() {
        return GraphQLScalarType.newScalar()
                .name("Date")
                .description("Java 8 LocalDate as scalar.")
                .coercing(new Coercing<Object, Object>() {
                    @Override
                    public String serialize(final Object dataFetcherResult) {
                        if (dataFetcherResult instanceof LocalDate) {
                            return dataFetcherResult.toString();
                        } else {
                            throw new CoercingSerializeException("Expected a LocalDate object.");
                        }
                    }

                    @Override
                    public LocalDate parseValue(final Object input) {
                        try {
                            if (input instanceof String) {
                                return LocalDate.parse((String) input);
                            } else {
                                throw new CoercingParseValueException("Expected a String");
                            }
                        } catch (DateTimeParseException e) {
                            throw new CoercingParseValueException(String.format("Not a valid date: '%s'.", input), e
                            );
                        }
                    }

                    @Override
                    public LocalDate parseLiteral(final Object input) {
                        if (input instanceof StringValue) {
                            try {
                                return LocalDate.parse(((StringValue) input).getValue());
                            } catch (DateTimeParseException e) {
                                throw new CoercingParseLiteralException(e);
                            }
                        } else {
                            throw new CoercingParseLiteralException("Expected a StringValue.");
                        }
                    }
                }).build();
    }

    @Bean
    RuntimeWiringConfigurer configurer() {
        GraphQLScalarType scalarType = dateScalar();
        return (builder) -> builder.scalar(scalarType);
    }
}

With this configuration:使用此配置:

build.gradle build.gradle

    implementation 'org.springframework.boot:spring-boot-starter-graphql'
    testImplementation 'org.springframework.graphql:spring-graphql'
    testImplementation 'org.springframework.graphql:spring-graphql-test'

And when I run this test I got:当我运行这个测试时,我得到了:

[ValidationError{validationErrorType=NonExecutableDefinition, queryPath=null, message=Validation error of type NonExecutableDefinition: The Date definition is not executable., locations=[SourceLocation{line=1, column=1}], description='The Date definition is not executable.'},
....

I follow some tutos and I think nothing is wrong with my code?我遵循了一些教程,我认为我的代码没有问题?

From what I figured out, the problem was the 'org.springframework.boot:spring-boot-starter-graphql' this is a new dependency and all the tutorials use 'com.graphql-java-kickstart'.据我所知,问题出在“org.springframework.boot:spring-boot-starter-graphql”,这是一个新的依赖项,所有教程都使用“com.graphql-java-kickstart”。 I made a couple of changes in your code and for my implementation I was using a JPA repository "DateModelRepository" replace it using your own repository.我对您的代码进行了一些更改,对于我的实现,我使用了 JPA 存储库“DateModelRepository”使用您自己的存储库替换它。

@Configuration
public class DateScalarConfiguration  {
@Bean
public RuntimeWiringConfigurer dateWiring(DateModelRepository dateModelRepository){
var dateScalar = GraphQLScalarType.newScalar()
            .name("Date")
            .description("Java 8 LocalDate as scalar.")
            .coercing(new Coercing<Object, Object>() {
                @Override
                public String serialize(final Object dataFetcherResult) {
                    if (dataFetcherResult instanceof LocalDate) {
                        return dataFetcherResult.toString();
                    } else {
                        throw new CoercingSerializeException("Expected a LocalDate object.");
                    }
                }

                @Override
                public LocalDate parseValue(final Object input) {
                    try {
                        if (input instanceof String) {
                            return LocalDate.parse((String) input);
                        } else {
                            throw new CoercingParseValueException("Expected a String");
                        }
                    } catch (DateTimeParseException e) {
                        throw new CoercingParseValueException(String.format("Not a valid date: '%s'.", input), e
                        );
                    }
                }

                @Override
                public LocalDate parseLiteral(final Object input) {
                    if (input instanceof StringValue) {
                        try {
                            return LocalDate.parse(((StringValue) input).getValue());
                        } catch (DateTimeParseException e) {
                            throw new CoercingParseLiteralException(e);
                        }
                    } else {
                        throw new CoercingParseLiteralException("Expected a StringValue.");
                    }
                }
            }).build();
}

return wiringBuilder -> wiringBuilder.scalar(dateScalar)
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM