Federation
Spring for GraphQL 為 federation-jvm 程式庫提供整合,該程式庫使用 GraphQL Java 初始化聯邦服務圖中的子圖架構。詳情請參閱 Apollo Federation 和 Subgraph 規格。
設定
若要啟用整合,請在您的設定中宣告 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 方法參數是從實體的 "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" 輸入映射中的具名值,也會轉換為具類型物件。 |
|
實體的完整 "representation" 輸入映射。 |
|
當使用單一控制器方法載入給定類型的所有實體時,"representation" 輸入映射的列表。 |
|
用於從 |
|
用於從 |
|
用於從 |
|
從 Spring Security 內容取得(如果可用)。 |
|
用於從 Spring Security 內容存取 |
|
用於透過 |
|
用於從 |
|
用於直接存取底層 |
@EntityMapping
方法可以傳回 Mono
、CompletableFuture
、Callable
或實際實體。