Search in sources :

Example 26 with ExecutionResult

use of graphql.ExecutionResult in project OpenTripPlanner by opentripplanner.

the class GraphIndex method getGraphQLResponse.

public Response getGraphQLResponse(String query, Map<String, Object> variables, String operationName) {
    ExecutionResult executionResult = graphQL.execute(query, operationName, null, variables);
    Response.ResponseBuilder res = Response.status(Response.Status.OK);
    HashMap<String, Object> content = new HashMap<>();
    if (!executionResult.getErrors().isEmpty()) {
        res = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        content.put("errors", executionResult.getErrors());
    }
    if (executionResult.getData() != null) {
        content.put("data", executionResult.getData());
    }
    return res.entity(content).build();
}
Also used : Response(javax.ws.rs.core.Response) HashMap(java.util.HashMap) ExecutionResult(graphql.ExecutionResult)

Example 27 with ExecutionResult

use of graphql.ExecutionResult in project carbon-apimgt by wso2.

the class QueryAnalyzer method analyseQueryComplexity.

/**
 * This method analyses the query complexity.
 *
 * @param fieldComplexityCalculator Field Complexity Calculator
 * @param maxQueryComplexity        Maximum query complexity value
 * @param payload                   payload of the request
 * @return true, if query complexity does not exceed the maximum or false, if query complexity exceeds the maximum
 */
public QueryAnalyzerResponseDTO analyseQueryComplexity(int maxQueryComplexity, String payload, FieldComplexityCalculator fieldComplexityCalculator) {
    if (log.isDebugEnabled()) {
        log.debug("Analyzing query complexity for " + payload + " and max complexity: " + maxQueryComplexity);
    }
    QueryAnalyzerResponseDTO queryAnalyzerResponseDTO = new QueryAnalyzerResponseDTO();
    // Otherwise, bypass the check.
    if (maxQueryComplexity > 0) {
        MaxQueryComplexityInstrumentation maxQueryComplexityInstrumentation = new MaxQueryComplexityInstrumentation(maxQueryComplexity, fieldComplexityCalculator);
        GraphQL runtime = GraphQL.newGraphQL(schema).instrumentation(maxQueryComplexityInstrumentation).build();
        ExecutionResult executionResult = runtime.execute(payload);
        List<GraphQLError> errors = executionResult.getErrors();
        if (errors.size() > 0) {
            for (GraphQLError error : errors) {
                queryAnalyzerResponseDTO.addErrorToList((error.getMessage()));
            }
            // TODO: https://github.com/wso2/carbon-apimgt/issues/8147
            queryAnalyzerResponseDTO.getErrorList().removeIf(s -> s.contains("non-nullable"));
            if (queryAnalyzerResponseDTO.getErrorList().size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Maximum query complexity was not exceeded");
                }
                queryAnalyzerResponseDTO.setSuccess(true);
            } else {
                log.error(queryAnalyzerResponseDTO.getErrorList());
                queryAnalyzerResponseDTO.getErrorList().clear();
                queryAnalyzerResponseDTO.addErrorToList("maximum query complexity exceeded");
            }
            queryAnalyzerResponseDTO.setSuccess(false);
            return queryAnalyzerResponseDTO;
        }
    }
    queryAnalyzerResponseDTO.setSuccess(true);
    return queryAnalyzerResponseDTO;
}
Also used : GraphQL(graphql.GraphQL) GraphQLError(graphql.GraphQLError) ExecutionResult(graphql.ExecutionResult) QueryAnalyzerResponseDTO(org.wso2.carbon.apimgt.common.gateway.dto.QueryAnalyzerResponseDTO) MaxQueryComplexityInstrumentation(graphql.analysis.MaxQueryComplexityInstrumentation)

Example 28 with ExecutionResult

use of graphql.ExecutionResult in project engine by craftercms.

the class SiteGraphQLController method handleRequest.

protected Map<String, Object> handleRequest(String query, String operationName, Map<String, Object> variables) {
    SiteContext siteContext = SiteContext.getCurrent();
    RequestContext requestContext = RequestContext.getCurrent();
    GraphQL graphQL = siteContext.getGraphQL();
    if (Objects.isNull(graphQL)) {
        logger.warn("GraphQL schema has not been initialized for site {}", siteContext.getSiteName());
        return Collections.singletonMap("errors", Collections.singletonList(Collections.singletonMap("message", "GraphQL schema has not been initialized for site " + siteContext.getSiteName())));
    }
    ExecutionInput.Builder executionInput = newExecutionInput().query(query).operationName(operationName).variables(variables).context(requestContext);
    StopWatch watch = new StopWatch("graphql - " + operationName);
    watch.start("query");
    ExecutionResult result = graphQL.execute(executionInput);
    watch.stop();
    if (logger.isTraceEnabled()) {
        logger.trace(watch.prettyPrint());
    }
    return result.toSpecification();
}
Also used : SiteContext(org.craftercms.engine.service.context.SiteContext) GraphQL(graphql.GraphQL) ExecutionResult(graphql.ExecutionResult) RequestContext(org.craftercms.commons.http.RequestContext) ExecutionInput.newExecutionInput(graphql.ExecutionInput.newExecutionInput) ExecutionInput(graphql.ExecutionInput) StopWatch(org.springframework.util.StopWatch)

Example 29 with ExecutionResult

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

the class ExecutionStrategy method resolveField.

/**
 * Called to fetch a value for a field and resolve it further in terms of the graphql query.  This will call
 * #fetchField followed by #completeField and the completed {@link ExecutionResult} is returned.
 * <p>
 * An execution strategy can iterate the fields to be executed and call this method for each one
 * <p>
 * Graphql fragments mean that for any give logical field can have one or more {@link Field} values associated with it
 * in the query, hence the fieldList.  However the first entry is representative of the field for most purposes.
 *
 * @param executionContext contains the top level execution parameters
 * @param parameters       contains the parameters holding the fields to be executed and source object
 *
 * @return an {@link ExecutionResult}
 *
 * @throws NonNullableFieldWasNullException if a non null field resolves to a null value
 */
protected CompletableFuture<ExecutionResult> resolveField(ExecutionContext executionContext, ExecutionStrategyParameters parameters) {
    GraphQLFieldDefinition fieldDef = getFieldDef(executionContext, parameters, parameters.getField().get(0));
    Instrumentation instrumentation = executionContext.getInstrumentation();
    InstrumentationContext<ExecutionResult> fieldCtx = instrumentation.beginField(new InstrumentationFieldParameters(executionContext, fieldDef, fieldTypeInfo(parameters, fieldDef)));
    CompletableFuture<ExecutionResult> result = fetchField(executionContext, parameters).thenCompose((fetchedValue) -> completeField(executionContext, parameters, fetchedValue));
    fieldCtx.onDispatched(result);
    result.whenComplete(fieldCtx::onCompleted);
    return result;
}
Also used : GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) Instrumentation(graphql.execution.instrumentation.Instrumentation) ExecutionResult(graphql.ExecutionResult) InstrumentationFieldParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldParameters)

Example 30 with ExecutionResult

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

the class ExecutionStrategy method handleNonNullException.

protected ExecutionResult handleNonNullException(ExecutionContext executionContext, CompletableFuture<ExecutionResult> result, Throwable e) {
    ExecutionResult executionResult = null;
    if (e instanceof NonNullableFieldWasNullException) {
        assertNonNullFieldPrecondition((NonNullableFieldWasNullException) e, result);
        if (!result.isDone()) {
            executionResult = new ExecutionResultImpl(null, executionContext.getErrors());
            result.complete(executionResult);
        }
    } else if (e instanceof CompletionException && e.getCause() instanceof NonNullableFieldWasNullException) {
        assertNonNullFieldPrecondition((NonNullableFieldWasNullException) e.getCause(), result);
        if (!result.isDone()) {
            executionResult = new ExecutionResultImpl(null, executionContext.getErrors());
            result.complete(executionResult);
        }
    } else {
        result.completeExceptionally(e);
    }
    return executionResult;
}
Also used : ExecutionResultImpl(graphql.ExecutionResultImpl) CompletionException(java.util.concurrent.CompletionException) ExecutionResult(graphql.ExecutionResult)

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