Federation
Spring for GraphQL 为 federation-jvm 库提供了一个集成,该库使用 GraphQL Java,用于初始化联合服务图中子图的架构。 有关详细信息,请参阅 Apollo Federation 和 Subgraph 规范。
配置
要启用集成,请声明FederationSchemaFactory
bean 的 Bean 和插件
it intoGraphQlSource.Builder
.例如,使用 Spring Boot:
@Configuration
public class FederationConfig {
@Bean
public GraphQlSourceBuilderCustomizer customizer(FederationSchemaFactory factory) {
return builder -> builder.schemaFactory(factory::createGraphQLSchema);
}
@Bean
public FederationSchemaFactory schemaFactory() {
return new FederationSchemaFactory();
}
}
现在,子图服务的架构可以扩展联合类型:
type Book @key(fields: "id") @extends {
id: ID! @external
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
@EntityMapping
一@EntityMapping
方法可以加载联合类型实例以响应来自 Federation Gateway 的 _entities 查询。例如:
例如:
@Controller
private static class BookController {
@EntityMapping
public Book book(@Argument int id) { (1)
// ...
}
@SchemaMapping
public Author author(Book book) { (2)
// ...
}
}
1 | 这@Argument method 参数从 的 “representation” 输入映射中解析
实体。完整的 “representation” 输入Map 也可以解决。请参阅支持的方法签名
method 参数和返回值类型。 |
2 | @SchemaMapping 方法可用于图形的其余部分。 |
一@EntityMapping
方法可以批量加载给定类型的联合实体。为此,
声明@Argument
method 参数作为列表,并返回相应的实体
实例作为列表。
例如:
@Controller
private static class BookController {
@EntityMapping
public List<Book> book(@Argument List<Integer> idList) { (1)
// ... return books in the same order
}
@BatchMapping
public Map<Book, Author> author(List<Book> books) { (2)
// ...
}
}
1 | 这idList 命名约定有助于将参数名称去复数化,以便
在 “representation” input map 中查找正确的值。您还可以设置
argument name 的 Bean S 的 Intent S 的 |
2 | @BatchMapping 方法可用于图形的其余部分。 |
方法签名
实体映射方法支持以下参数:
方法参数 | 描述 |
---|---|
|
用于从 “representation” 输入映射访问命名值,也转换为类型化 Object。 |
|
实体的完整 “representation” 输入映射。 |
|
使用单个控制器方法加载时的 “representation” input maps 列表 给定类型的所有实体。 |
|
要从主 |
|
要从本地 |
|
要从 |
|
从 Spring Security 上下文获取(如果可用)。 |
|
要访问 |
|
要通过 |
|
要访问 |
|
用于直接访问底层 |
@EntityMapping
方法可以返回Mono
,CompletableFuture
,Callable
或实际实体。