Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try to make federation work (with reactive) #1898

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package io.smallrye.graphql.bootstrap;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.apollographql.federation.graphqljava._Entity;

import graphql.execution.Async;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.DelegatingDataFetchingEnvironment;
Expand All @@ -20,7 +22,7 @@
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLOutputType;

class FederationDataFetcher implements DataFetcher<List<Object>> {
class FederationDataFetcher implements DataFetcher<CompletableFuture<List<Object>>> {

private final GraphQLObjectType queryType;
private final GraphQLCodeRegistry codeRegistry;
Expand All @@ -31,10 +33,11 @@ public FederationDataFetcher(GraphQLObjectType queryType, GraphQLCodeRegistry co
}

@Override
public List<Object> get(DataFetchingEnvironment environment) throws Exception {
return environment.<List<Map<String, Object>>> getArgument(_Entity.argumentName).stream()
.map(representations -> fetchEntities(environment, representations))
.collect(toList());
public CompletableFuture<List<Object>> get(DataFetchingEnvironment environment) throws Exception {
return sequence(environment.<List<Map<String, Object>>> getArgument(_Entity.argumentName).stream()
.map(representations -> fetchEntities(environment, representations)).map(Async::toCompletableFuture)
.collect(Collectors.toList()));

}

private Object fetchEntities(DataFetchingEnvironment env, Map<String, Object> representations) {
Expand Down Expand Up @@ -90,4 +93,11 @@ public <T> T getArgumentOrDefault(String name, T defaultValue) {
throw new RuntimeException("can't fetch data from " + field, e);
}
}

static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> com) {
return CompletableFuture.allOf(com.toArray(new CompletableFuture<?>[0]))
.thenApply(v -> com.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
}
Loading