在 Spring boot 中以编程方式指定 GraphQL 模式

问题描述 投票:0回答:1

我使用“代码优先”方法使用 graphql-java-annotations 定义架构,而不是在单独的

.graphqls
文件中定义架构。

我尝试使用

GraphQlSourceBuilderCustomizer
指定架构,如文档中提到的,但出现以下异常:

org.springframework.graphql.execution.MissingSchemaException:未配置 GraphQL 架构定义。 在

[电子邮件受保护]/java.util.Optional.orElseThrow(Optional.java:403) 在应用程序//org.springframework.graphql.execution.DefaultGraphQlSourceBuilder.build(DefaultGraphQlSourceBuilder.java:136) 在应用程序//org.springframework.boot.autoconfigure.graphql.GraphQlAutoConfiguration.graphQlSource(GraphQlAutoConfiguration.java:90)

这是我的配置类。有谁知道我哪里错了?

@Configuration public class GraphQLConfiguration { @Bean public GraphQlSourceBuilderCustomizer sourceBuilderCustomizer() { GraphQLSchema graphQLSchema = AnnotationsSchemaCreator.newAnnotationsSchema() .query(GraphQLQuery.class) .build(); return graphQlSourceBuilder -> graphQlSourceBuilder.configureGraphQl(graphQLBuilder -> graphQLBuilder.schema(graphQLSchema)); } }
    
java spring spring-boot graphql graphql-java
1个回答
0
投票
根据

这个问题的答案,很明显 Spring-Graphql 需要具有有效架构的 schema.graphqls 文件,否则它将无法加载。

有两种可能的解决方法:

    在资源文件夹中创建一个虚拟“.graphqls”文件并在其中添加一个虚拟类型
  1. 提供具有虚拟类型的内存中 graphql 定义
选项#1很简单,所以我将给出选项#2的示例代码:

@Bean @Lazy @ConditionalOnBean({GraphQLSchema.class, DataFetcherExceptionHandler.class}) public GraphQlSourceBuilderCustomizer federationTransform(GraphQLSchema schema, DataFetcherExceptionHandler exceptionHandler) { String ss = """ type Meta { count: Int } type Query { NotificationsMeta: Meta } """; return builder -> { URL schemaUrl = InMemoryURLFactory.getInstance().build("/graphql.schema", ss); builder.schemaResources(new UrlResource(schemaUrl)); builder.configureGraphQl(graphQLBuilder -> graphQLBuilder.schema(schema) .defaultDataFetcherExceptionHandler(exceptionHandler)); }; }
这样,内存中的模式将被忽略,并使用 

GraphQLSchema

 对象表示的模式。
注意:InMemoryURLFactory 可以从
这个 Stack Overflow 答案 获得

© www.soinside.com 2019 - 2024. All rights reserved.