联合
Spring for GraphQL 提供了与 federation-jvm 库的集成,该库使用 GraphQL Java 初始化联合服务图中的子图模式。详情请参阅 Apollo Federation 和 子图规范。
配置
要启用此集成,请在配置中声明一个 FederationSchemaFactory
bean,并将其接入 GraphQlSource.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
方法可以响应联合网关发送的 _entities query 查询来加载联合类型实例。例如
@Controller
private static class BookController {
@EntityMapping
public Book book(@Argument int id) { (1)
// ...
}
@SchemaMapping
public Author author(Book book) { (2)
// ...
}
}
1 | @Argument 方法参数从实体的 "representation" 输入映射中解析。完整的 "representation" 输入 Map 也可以被解析。请参阅 方法签名 了解支持的方法参数和返回值类型。 |
2 | @SchemaMapping 方法可用于图的其他部分。 |
一个 @EntityMapping
方法可以批量加载给定类型的联合实体。为此,请将 @Argument
方法参数声明为列表,并按相同顺序返回相应的实体实例列表。
例如
@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" 输入映射中查找正确的值。您也可以通过注解设置参数名称。 |
2 | @BatchMapping 方法可用于图的其他部分。 |
方法签名
实体映射方法支持以下参数
方法参数 | 描述 |
---|---|
|
用于访问 "representation" 输入映射中的命名值,也可转换为类型化的 Object。 |
|
实体的完整 "representation" 输入映射。 |
|
当使用单个控制器方法加载给定类型的所有实体时,"representation" 输入映射列表。 |
|
用于访问 |
|
用于访问 |
|
用于从 |
|
如果可用,从 Spring Security 上下文中获取。 |
|
用于从 Spring Security 上下文访问 |
|
用于通过 |
|
用于从 |
|
用于直接访问底层的 |
@EntityMapping
方法可以返回 Mono
、CompletableFuture
、Callable
或实际实体。