联合
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 查询,加载联合类型实例。例如:
@Controller
private static class BookController {
@EntityMapping
public Book book(@Argument int id) { (1)
// ...
}
@SchemaMapping
public Author author(Book book) { (2)
// ...
}
}
| 1 | @Argument 方法参数从实体的“表示”输入映射中解析。完整的“表示”输入 Map 也可以被解析。有关支持的方法参数和返回值类型,请参阅方法签名。 |
| 2 | @SchemaMapping 方法可用于图的其他部分。 |
您可以通过接受一个 ID List 并返回一个实体 List 或 Flux 来一起加载相同类型的联合实体
@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 命名约定有助于取消参数名称的复数形式,以便在“表示”输入映射中查找正确的值。您也可以通过注解设置参数名称。 |
| 2 | @BatchMapping 方法可用于图的其他部分。 |
您可以使用 DataLoader 加载联合实体
@Controller
private static class BookController {
@Autowired
public DataLoaderBookController(BatchLoaderRegistry registry) { (1)
registry.forTypePair(Integer.class, Book.class).registerBatchLoader((bookIds, environment) -> {
// load entities...
});
}
@EntityMapping
public Future<Book> book(@Argument int id, DataLoader<Integer, Book> dataLoader) { (2)
return dataLoader.load(id);
}
@BatchMapping
public Map<Book, Author> author(List<Book> books) { (3)
// ...
}
}
| 1 | 为联合实体类型注册一个批量加载器。 |
| 2 | 声明一个 DataLoader 参数给 @EntityMapping 方法。 |
| 3 | @BatchMapping 方法可用于图的其他部分。 |
方法签名
实体映射方法支持以下参数
| 方法参数 | 描述 |
|---|---|
|
用于从“表示”输入映射访问命名值,并将其转换为类型化对象。 |
|
实体的完整“表示”输入映射。 |
|
当使用单个控制器方法加载给定类型的所有实体时,“表示”输入映射列表。 |
|
用于访问 |
|
用于访问 |
|
用于访问 |
|
如果可用,从 Spring Security 上下文获取。 |
|
用于从 Spring Security 上下文访问 |
|
通过 |
|
用于从 |
|
直接访问底层的 |
|
使用 |
@EntityMapping 方法可以返回 Mono、CompletableFuture、Callable 或实际实体。