Search in sources :

Example 31 with ExecutionResult

use of graphql.ExecutionResult in project graphql-java by graphql-java.

the class ExecutorServiceExecutionStrategy method execute.

@Override
public CompletableFuture<ExecutionResult> execute(final ExecutionContext executionContext, final ExecutionStrategyParameters parameters) {
    if (executorService == null) {
        return new AsyncExecutionStrategy().execute(executionContext, parameters);
    }
    Instrumentation instrumentation = executionContext.getInstrumentation();
    InstrumentationExecutionStrategyParameters instrumentationParameters = new InstrumentationExecutionStrategyParameters(executionContext, parameters);
    InstrumentationContext<ExecutionResult> executionStrategyCtx = instrumentation.beginExecutionStrategy(instrumentationParameters);
    Map<String, List<Field>> fields = parameters.getFields();
    Map<String, Future<CompletableFuture<ExecutionResult>>> futures = new LinkedHashMap<>();
    for (String fieldName : fields.keySet()) {
        final List<Field> currentField = fields.get(fieldName);
        ExecutionPath fieldPath = parameters.getPath().segment(fieldName);
        ExecutionStrategyParameters newParameters = parameters.transform(builder -> builder.field(currentField).path(fieldPath));
        Callable<CompletableFuture<ExecutionResult>> resolveField = () -> resolveField(executionContext, newParameters);
        futures.put(fieldName, executorService.submit(resolveField));
    }
    CompletableFuture<ExecutionResult> overallResult = new CompletableFuture<>();
    executionStrategyCtx.onDispatched(overallResult);
    try {
        Map<String, Object> results = new LinkedHashMap<>();
        for (String fieldName : futures.keySet()) {
            ExecutionResult executionResult;
            try {
                executionResult = futures.get(fieldName).get().join();
            } catch (CompletionException e) {
                if (e.getCause() instanceof NonNullableFieldWasNullException) {
                    assertNonNullFieldPrecondition((NonNullableFieldWasNullException) e.getCause());
                    results = null;
                    break;
                } else {
                    throw e;
                }
            }
            results.put(fieldName, executionResult != null ? executionResult.getData() : null);
        }
        ExecutionResultImpl executionResult = new ExecutionResultImpl(results, executionContext.getErrors());
        overallResult.complete(executionResult);
        overallResult.whenComplete(executionStrategyCtx::onCompleted);
        return overallResult;
    } catch (InterruptedException | ExecutionException e) {
        executionStrategyCtx.onCompleted(null, e);
        throw new GraphQLException(e);
    }
}
Also used : Instrumentation(graphql.execution.instrumentation.Instrumentation) LinkedHashMap(java.util.LinkedHashMap) Field(graphql.language.Field) CompletableFuture(java.util.concurrent.CompletableFuture) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters) List(java.util.List) GraphQLException(graphql.GraphQLException) ExecutionException(java.util.concurrent.ExecutionException) ExecutionResult(graphql.ExecutionResult) CompletionException(java.util.concurrent.CompletionException) ExecutionResultImpl(graphql.ExecutionResultImpl) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters)

Example 32 with ExecutionResult

use of graphql.ExecutionResult in project graphql-java by graphql-java.

the class ChainedInstrumentation method instrumentExecutionResult.

@Override
public CompletableFuture<ExecutionResult> instrumentExecutionResult(ExecutionResult executionResult, InstrumentationExecutionParameters parameters) {
    CompletableFuture<List<ExecutionResult>> resultsFuture = Async.eachSequentially(instrumentations, (instrumentation, index, prevResults) -> {
        InstrumentationState state = getState(instrumentation, parameters.getInstrumentationState());
        ExecutionResult lastResult = prevResults.size() > 0 ? prevResults.get(prevResults.size() - 1) : executionResult;
        return instrumentation.instrumentExecutionResult(lastResult, parameters.withNewState(state));
    });
    return resultsFuture.thenApply((results) -> results.isEmpty() ? executionResult : results.get(results.size() - 1));
}
Also used : List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ExecutionResult(graphql.ExecutionResult)

Example 33 with ExecutionResult

use of graphql.ExecutionResult in project graphql-java by graphql-java.

the class AsyncExecutionStrategy method execute.

@Override
public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {
    Instrumentation instrumentation = executionContext.getInstrumentation();
    InstrumentationExecutionStrategyParameters instrumentationParameters = new InstrumentationExecutionStrategyParameters(executionContext, parameters);
    InstrumentationContext<ExecutionResult> executionStrategyCtx = instrumentation.beginExecutionStrategy(instrumentationParameters);
    Map<String, List<Field>> fields = parameters.getFields();
    List<String> fieldNames = new ArrayList<>(fields.keySet());
    List<CompletableFuture<ExecutionResult>> futures = new ArrayList<>();
    for (String fieldName : fieldNames) {
        List<Field> currentField = fields.get(fieldName);
        ExecutionPath fieldPath = parameters.getPath().segment(fieldName);
        ExecutionStrategyParameters newParameters = parameters.transform(builder -> builder.field(currentField).path(fieldPath));
        if (isDeferred(executionContext, newParameters, currentField)) {
            continue;
        }
        CompletableFuture<ExecutionResult> future = resolveField(executionContext, newParameters);
        futures.add(future);
    }
    CompletableFuture<ExecutionResult> overallResult = new CompletableFuture<>();
    executionStrategyCtx.onDispatched(overallResult);
    Async.each(futures).whenComplete(handleResults(executionContext, fieldNames, overallResult));
    overallResult.whenComplete(executionStrategyCtx::onCompleted);
    return overallResult;
}
Also used : ArrayList(java.util.ArrayList) Instrumentation(graphql.execution.instrumentation.Instrumentation) ExecutionResult(graphql.ExecutionResult) Field(graphql.language.Field) CompletableFuture(java.util.concurrent.CompletableFuture) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters) List(java.util.List) ArrayList(java.util.ArrayList) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters)

Example 34 with ExecutionResult

use of graphql.ExecutionResult in project graphql-java by graphql-java.

the class ConcernsExamples method contextHelper.

private void contextHelper() {
    // 
    // this could be code that authorises the user in some way and sets up enough context
    // that can be used later inside data fetchers allowing them
    // to do their job
    // 
    UserContext contextForUser = YourGraphqlContextBuilder.getContextForUser(getCurrentUser());
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().context(contextForUser).build();
    ExecutionResult executionResult = graphQL.execute(executionInput);
    // ...
    // 
    // later you are able to use this context object when a data fetcher is invoked
    // 
    DataFetcher dataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            UserContext userCtx = environment.getContext();
            Long businessObjId = environment.getArgument("businessObjId");
            return invokeBusinessLayerMethod(userCtx, businessObjId);
        }
    };
}
Also used : ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput) DataFetcher(graphql.schema.DataFetcher) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment)

Example 35 with ExecutionResult

use of graphql.ExecutionResult in project graphql-java by graphql-java.

the class ExecutionExamples method simpleAsyncQueryExecution.

@SuppressWarnings("Convert2MethodRef")
private void simpleAsyncQueryExecution() throws Exception {
    GraphQL graphQL = buildSchema();
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }").build();
    CompletableFuture<ExecutionResult> promise = graphQL.executeAsync(executionInput);
    promise.thenAccept(executionResult -> {
        // here you might send back the results as JSON over HTTP
        encodeResultToJsonAndSendResponse(executionResult);
    });
    promise.join();
}
Also used : GraphQL(graphql.GraphQL) ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput)

Aggregations

ExecutionResult (graphql.ExecutionResult)42 GraphQL (graphql.GraphQL)17 List (java.util.List)10 GraphQLSchema (graphql.schema.GraphQLSchema)9 ExecutionInput (graphql.ExecutionInput)8 Instrumentation (graphql.execution.instrumentation.Instrumentation)8 Field (graphql.language.Field)8 ExecutionResultImpl (graphql.ExecutionResultImpl)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 GraphQLError (graphql.GraphQLError)6 GraphQLFieldDefinition (graphql.schema.GraphQLFieldDefinition)6 LinkedHashMap (java.util.LinkedHashMap)6 GraphQLObjectType (graphql.schema.GraphQLObjectType)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 InstrumentationExecutionStrategyParameters (graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters)4 HashMap (java.util.HashMap)4 Collectors.toList (java.util.stream.Collectors.toList)3 InstrumentationFieldCompleteParameters (graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters)2 GraphQLList (graphql.schema.GraphQLList)2