Search in sources :

Example 16 with GraphQL

use of graphql.GraphQL 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 17 with GraphQL

use of graphql.GraphQL 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 18 with GraphQL

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

the class BatchingExamples method starWarsExample.

void starWarsExample() {
    // a batch loader function that will be called with N or more keys for batch loading
    BatchLoader<String, Object> characterBatchLoader = new BatchLoader<String, Object>() {

        @Override
        public CompletionStage<List<Object>> load(List<String> keys) {
            // 
            return CompletableFuture.supplyAsync(() -> getCharacterDataViaBatchHTTPApi(keys));
        }
    };
    // a data loader for characters that points to the character batch loader
    DataLoader<String, Object> characterDataLoader = new DataLoader<>(characterBatchLoader);
    // 
    // use this data loader in the data fetchers associated with characters and put them into
    // the graphql schema (not shown)
    // 
    DataFetcher heroDataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            // R2D2
            return characterDataLoader.load("2001");
        }
    };
    DataFetcher friendsDataFetcher = new DataFetcher() {

        @Override
        public Object get(DataFetchingEnvironment environment) {
            StarWarsCharacter starWarsCharacter = environment.getSource();
            List<String> friendIds = starWarsCharacter.getFriendIds();
            return characterDataLoader.loadMany(friendIds);
        }
    };
    // 
    // DataLoaderRegistry is a place to register all data loaders in that needs to be dispatched together
    // in this case there is 1 but you can have many
    // 
    DataLoaderRegistry registry = new DataLoaderRegistry();
    registry.register("character", characterDataLoader);
    // 
    // this instrumentation implementation will dispatched all the dataloaders
    // as each level fo the graphql query is executed and hence make batched objects
    // available to the query and the associated DataFetchers
    // 
    DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation(registry);
    // 
    // now build your graphql object and execute queries on it.
    // the data loader will be invoked via the data fetchers on the
    // schema fields
    // 
    GraphQL graphQL = GraphQL.newGraphQL(buildSchema()).instrumentation(dispatcherInstrumentation).build();
}
Also used : GraphQL(graphql.GraphQL) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) BatchLoader(org.dataloader.BatchLoader) DataLoader(org.dataloader.DataLoader) DataLoaderRegistry(org.dataloader.DataLoaderRegistry) List(java.util.List) DataFetcher(graphql.schema.DataFetcher)

Example 19 with GraphQL

use of graphql.GraphQL 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)

Example 20 with GraphQL

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

the class ReadmeExamples method executionStrategies.

void executionStrategies() {
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, /* core pool size 2 thread */
    2, /* max pool size 2 thread */
    30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());
    GraphQL graphQL = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema).queryExecutionStrategy(new ExecutorServiceExecutionStrategy(threadPoolExecutor)).mutationExecutionStrategy(new AsyncExecutionStrategy()).subscriptionExecutionStrategy(new AsyncExecutionStrategy()).build();
}
Also used : GraphQL(graphql.GraphQL) ExecutorServiceExecutionStrategy(graphql.execution.ExecutorServiceExecutionStrategy) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) AsyncExecutionStrategy(graphql.execution.AsyncExecutionStrategy)

Aggregations

GraphQL (graphql.GraphQL)25 ExecutionResult (graphql.ExecutionResult)18 GraphQLSchema (graphql.schema.GraphQLSchema)13 ExecutionInput (graphql.ExecutionInput)6 RuntimeWiring (graphql.schema.idl.RuntimeWiring)5 RuntimeWiring.newRuntimeWiring (graphql.schema.idl.RuntimeWiring.newRuntimeWiring)5 SchemaGenerator (graphql.schema.idl.SchemaGenerator)5 SchemaParser (graphql.schema.idl.SchemaParser)5 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)5 GraphQLError (graphql.GraphQLError)4 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)4 List (java.util.List)4 DataLoaderRegistry (org.dataloader.DataLoaderRegistry)4 DataLoaderDispatcherInstrumentation (graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ExecutionInput.newExecutionInput (graphql.ExecutionInput.newExecutionInput)2 ExecutorServiceExecutionStrategy (graphql.execution.ExecutorServiceExecutionStrategy)2