Federation
Spring for GraphQL 提供了对 federation-jvm 库的集成,该库使用 GraphQL Java 初始化Federation服务图中的子图架构。 请参见 Apollo Federation 和 子图规范 以获取详细信息。
配置
要启用集成,请在您的配置中声明一个FederationSchemaFactory豆,并将其插入到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();
}
}
现在子图服务的模式可以扩展Federation类型:
type Book @key(fields: "id") @extends {
id: ID! @external
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
@EntityMapping
一个 @EntityMapping 方法可以加载Federation类型实例,响应于从Federation网关接收的
_entities查询。
例如:
@Controller
private static class BookController {
@EntityMapping
public Book book(@Argument int id) { (1)
// ...
}
@SchemaMapping
public Author author(Book book) { (2)
// ...
}
}
| 1 | The @Argument 方法参数是从实体的 |
| 2 | @SchemaMapping 方法可以用于图中的其余部分。 |
您可以接受id为List来一起加载相同类型的Federation实体,并返回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 | The idList naming convention helps to de-pluralize the parameter name in order to
look up the correct value in the "representation" input map. You can also set the
argument name through the annotation. |
| 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 | 注册Federation实体类型的批量加载器。 |
| 2 | 声明一个DataLoader参数给@EntityMapping方法。 |
| 3 | @BatchMapping 方法可以用于图中的其余部分。 |
方法签名
实体映射方法支持以下参数:
| 方法参数 | 描述 |
|---|---|
|
从"representation"输入映射中访问命名值,并将其转换为Typed对象。 |
|
实体的完整“表示”输入映射。 |
|
使用单个控制器方法加载给定类型的所有实体时,“表示”输入映射的列表。 |
|
从主 |
|
从 |
|
从 |
|
从 Spring Security上下文获取(如果可用的话)。 |
|
从Spring Security上下文中访问 |
|
通过 |
|
从 |
|
直接访问底层的 |
|
要加载使用 |
@EntityMapping 方法可以返回 Mono、CompletableFuture、Callable 或实际实体。