Java Code Examples for graphql.schema.DataFetcher

The following examples show how to use graphql.schema.DataFetcher. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 6 votes vote down vote up
DataFetcher<Optional<Bytes32>> getSendRawTransactionDataFetcher() {
  return dataFetchingEnvironment -> {
    try {
      final TransactionPool transactionPool =
          ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getTransactionPool();
      final Bytes rawTran = dataFetchingEnvironment.getArgument("data");

      final Transaction transaction = Transaction.readFrom(RLP.input(rawTran));
      final ValidationResult<TransactionInvalidReason> validationResult =
          transactionPool.addLocalTransaction(transaction);
      if (validationResult.isValid()) {
        return Optional.of(transaction.getHash());
      } else {
        throw new GraphQLException(GraphQLError.of(validationResult.getInvalidReason()));
      }
    } catch (final IllegalArgumentException | RLPException e) {
      throw new GraphQLException(GraphQLError.INVALID_PARAMS);
    }
  };
}
 
Example #2
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 6 votes vote down vote up
public DataFetcher<Optional<NormalBlockAdapter>> getBlockDataFetcher() {

    return dataFetchingEnvironment -> {
      final BlockchainQueries blockchain =
          ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getBlockchainQueries();
      final Long number = dataFetchingEnvironment.getArgument("number");
      final Bytes32 hash = dataFetchingEnvironment.getArgument("hash");
      if ((number != null) && (hash != null)) {
        throw new GraphQLException(GraphQLError.INVALID_PARAMS);
      }

      final Optional<BlockWithMetadata<TransactionWithMetadata, Hash>> block;
      if (number != null) {
        block = blockchain.blockByNumber(number);
        checkArgument(block.isPresent(), "Block number %s was not found", number);
      } else if (hash != null) {
        block = blockchain.blockByHash(Hash.wrap(hash));
        Preconditions.checkArgument(block.isPresent(), "Block hash %s was not found", hash);
      } else {
        block = blockchain.latestBlock();
      }
      return block.map(NormalBlockAdapter::new);
    };
  }
 
Example #3
Source Project: hypergraphql   Author: hypergraphql   File: HGQLSchemaWiring.java    License: Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition getBuiltField(FieldOfTypeConfig field, DataFetcher fetcher) {

        List<GraphQLArgument> args = new ArrayList<>();

        if (field.getTargetName().equals("String")) {
            args.add(defaultArguments.get("lang"));
        }

        if(field.getService() == null) {
            throw new HGQLConfigurationException("Value of 'service' for field '" + field.getName() + "' cannot be null");
        }

        String description = field.getId() + " (source: " + field.getService().getId() + ").";

        return newFieldDefinition()
                .name(field.getName())
                .argument(args)
                .description(description)
                .type(field.getGraphqlOutputType())
                .dataFetcher(fetcher)
                .build();
    }
 
Example #4
Source Project: samples   Author: graphql-java-kickstart   File: UppercaseDirective.java    License: MIT License 6 votes vote down vote up
@Override
public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> env) {
  GraphQLFieldDefinition field = env.getElement();
  GraphQLFieldsContainer parentType = env.getFieldsContainer();

  // build a data fetcher that transforms the given value to uppercase
  DataFetcher originalFetcher = env.getCodeRegistry().getDataFetcher(parentType, field);
  DataFetcher dataFetcher = DataFetcherFactories
      .wrapDataFetcher(originalFetcher, ((dataFetchingEnvironment, value) -> {
        if (value instanceof String) {
          return ((String) value).toUpperCase();
        }
        return value;
      }));

  // now change the field definition to use the new uppercase data fetcher
  env.getCodeRegistry().dataFetcher(parentType, field, dataFetcher);
  return field;
}
 
Example #5
Source Project: samples   Author: graphql-java-kickstart   File: RangeDirective.java    License: MIT License 6 votes vote down vote up
private DataFetcher createDataFetcher(DataFetcher originalFetcher) {
  return (env) -> {
    List<GraphQLError> errors = new ArrayList<>();
    env.getFieldDefinition().getArguments().stream().forEach(it -> {
      if (appliesTo(it)) {
        errors.addAll(apply(it, env, env.getArgument(it.getName())));
      }

      GraphQLInputType unwrappedInputType = Util.unwrapNonNull(it.getType());
      if (unwrappedInputType instanceof GraphQLInputObjectType) {
        GraphQLInputObjectType inputObjType = (GraphQLInputObjectType) unwrappedInputType;
        inputObjType.getFieldDefinitions().stream().filter(this::appliesTo).forEach(io -> {
          Map<String, Object> value = env.getArgument(it.getName());
          errors.addAll(apply(io, env, value.get(io.getName())));
        });
      }
    });

    Object returnValue = originalFetcher.get(env);
    if (errors.isEmpty()) {
      return returnValue;
    }
    return Util.mkDFRFromFetchedResult(errors, returnValue);
  };
}
 
Example #6
Source Project: rsocket-rpc-java   Author: rsocket   File: GraphQLDataFetchers.java    License: Apache License 2.0 6 votes vote down vote up
public static DataFetcher<Book> getBookByIdDataFetcher() {
  return dataFetchingEnvironment -> {
    String bookId = dataFetchingEnvironment.getArgument("id");
    System.out.println("looking for book id " + bookId);
    Book book = books.get(bookId);

    return book;
  };
}
 
Example #7
Source Project: rsocket-rpc-java   Author: rsocket   File: GraphQLDataFetchers.java    License: Apache License 2.0 6 votes vote down vote up
public static DataFetcher<Author> getAuthorDataFetcher() {
  return dataFetchingEnvironment -> {
    Book book = dataFetchingEnvironment.getSource();
    String authorId = book.getAuthor().getId();
    System.out.println("looking for author id " + authorId);
    return authors.get(authorId);
  };
}
 
Example #8
Source Project: rejoiner   Author: google   File: FuturesConverter.java    License: Apache License 2.0 6 votes vote down vote up
public static Instrumentation apiFutureInstrumentation() {
  return new SimpleInstrumentation() {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
        DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
      return (DataFetcher<Object>)
          dataFetchingEnvironment -> {
            Object data = dataFetcher.get(dataFetchingEnvironment);
            if (data instanceof ApiFuture) {
              return FutureConverter.toCompletableFuture(
                  apiFutureToListenableFuture((ApiFuture<?>) data));
            }
            return data;
          };
    }
  };
}
 
Example #9
Source Project: hypergraphql   Author: semantic-integration   File: HGQLSchemaWiring.java    License: Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition getBuiltField(FieldOfTypeConfig field, DataFetcher fetcher) {

        List<GraphQLArgument> args = new ArrayList<>();

        if (field.getTargetName().equals("String")) {
            args.add(defaultArguments.get("lang"));
        }

        if(field.getService() == null) {
            throw new HGQLConfigurationException("Value of 'service' for field '" + field.getName() + "' cannot be null");
        }

        String description = field.getId() + " (source: " + field.getService().getId() + ").";

        return newFieldDefinition()
                .name(field.getName())
                .argument(args)
                .description(description)
                .type(field.getGraphqlOutputType())
                .dataFetcher(fetcher)
                .build();
    }
 
Example #10
Source Project: graphql-spqr   Author: leangen   File: EnumMapToObjectTypeAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQLObjectType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLObjectType.Builder builder = GraphQLObjectType.newObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    Enum<E>[] keys = ClassUtils.<E>getRawType(getElementType(javaType, 0).getType()).getEnumConstants();
    Arrays.stream(keys).forEach(enumValue -> {
        String fieldName = enumMapper.getValueName(enumValue, buildContext.messageBundle);
        TypedElement element = new TypedElement(getElementType(javaType, 1), ClassUtils.getEnumConstantField(enumValue));
        buildContext.codeRegistry.dataFetcher(FieldCoordinates.coordinates(typeName, fieldName), (DataFetcher) e -> ((Map)e.getSource()).get(enumValue));
        builder.field(GraphQLFieldDefinition.newFieldDefinition()
                .name(fieldName)
                .description(enumMapper.getValueDescription(enumValue, buildContext.messageBundle))
                .deprecate(enumMapper.getValueDeprecationReason(enumValue, buildContext.messageBundle))
                .type(env.forElement(element).toGraphQLType(element.getJavaType()))
                .build());
    });
    return builder.build();
}
 
Example #11
Source Project: graphql-spqr   Author: leangen   File: OperationMapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a resolver for the <em>node</em> query as defined by the Relay GraphQL spec.
 * <p>This query only takes a singe argument called "id" of type String, and returns the object implementing the
 * <em>Node</em> interface to which the given id corresponds.</p>
 *
 * @param nodeQueriesByType A map of all queries whose return types implement the <em>Node</em> interface, keyed
 *                          by their corresponding GraphQL type name
 * @param relay Relay helper
 *
 * @return The node query resolver
 */
private DataFetcher<?> createNodeResolver(Map<String, String> nodeQueriesByType, Relay relay) {
    return env -> {
        String typeName;
        try {
            typeName = relay.fromGlobalId(env.getArgument(GraphQLId.RELAY_ID_FIELD_NAME)).getType();
        } catch (Exception e) {
            throw new IllegalArgumentException(env.getArgument(GraphQLId.RELAY_ID_FIELD_NAME) + " is not a valid Relay node ID");
        }
        if (!nodeQueriesByType.containsKey(typeName)) {
            throw new IllegalArgumentException(typeName + " is not a Relay node type or no registered query can fetch it by ID");
        }
        final GraphQLObjectType queryRoot = env.getGraphQLSchema().getQueryType();
        final GraphQLFieldDefinition nodeQueryForType = queryRoot.getFieldDefinition(nodeQueriesByType.get(typeName));

        return env.getGraphQLSchema().getCodeRegistry().getDataFetcher(queryRoot, nodeQueryForType).get(env);
    };
}
 
Example #12
Source Project: graphql-apigen   Author: Distelli   File: ResolverDataFetcher.java    License: Apache License 2.0 6 votes vote down vote up
public ResolverDataFetcher(DataFetcher fetcher, Resolver resolver, int listDepth) {
    this.fetcher = fetcher;
    this.resolver = resolver;
    this.listDepth = listDepth;
    if ( fetcher instanceof BatchedDataFetcher ) {
        this.isBatched = true;
    } else {
        try {
            Method getMethod = fetcher.getClass()
                .getMethod("get", DataFetchingEnvironment.class);
            this.isBatched = null != getMethod.getAnnotation(Batched.class);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example #13
Source Project: vertx-web   Author: vert-x3   File: GraphQLExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void completionStageDataFetcher() {
  DataFetcher<CompletionStage<List<Link>>> dataFetcher = environment -> {

    CompletableFuture<List<Link>> completableFuture = new CompletableFuture<>();

    retrieveLinksFromBackend(environment, ar -> {
      if (ar.succeeded()) {
        completableFuture.complete(ar.result());
      } else {
        completableFuture.completeExceptionally(ar.cause());
      }
    });

    return completableFuture;
  };

  RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", dataFetcher))
    .build();
}
 
Example #14
Source Project: vertx-web   Author: vert-x3   File: JsonResultsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .wiringFactory(new WiringFactory() {
      @Override
      public DataFetcher getDefaultDataFetcher(FieldWiringEnvironment environment) {
        return VertxPropertyDataFetcher.create(environment.getFieldDefinition().getName());
      }
    })
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #15
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 5 votes vote down vote up
DataFetcher<Optional<SyncStateAdapter>> getSyncingDataFetcher() {
  return dataFetchingEnvironment -> {
    final Synchronizer synchronizer =
        ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getSynchronizer();
    final Optional<SyncStatus> syncStatus = synchronizer.getSyncStatus();
    return syncStatus.map(SyncStateAdapter::new);
  };
}
 
Example #16
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 5 votes vote down vote up
DataFetcher<Optional<PendingStateAdapter>> getPendingStateDataFetcher() {
  return dataFetchingEnvironment -> {
    final TransactionPool txPool =
        ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getTransactionPool();
    return Optional.of(new PendingStateAdapter(txPool.getPendingTransactions()));
  };
}
 
Example #17
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 5 votes vote down vote up
DataFetcher<Optional<Wei>> getGasPriceDataFetcher() {
  return dataFetchingEnvironment -> {
    final MiningCoordinator miningCoordinator =
        ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getMiningCoordinator();

    return Optional.of(miningCoordinator.getMinTransactionGasPrice());
  };
}
 
Example #18
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 5 votes vote down vote up
DataFetcher<Optional<List<LogAdapter>>> getLogsDataFetcher() {
  return dataFetchingEnvironment -> {
    final GraphQLDataFetcherContext dataFetcherContext = dataFetchingEnvironment.getContext();
    final BlockchainQueries blockchainQuery = dataFetcherContext.getBlockchainQueries();

    final Map<String, Object> filter = dataFetchingEnvironment.getArgument("filter");

    final long currentBlock = blockchainQuery.getBlockchain().getChainHeadBlockNumber();
    final long fromBlock = (Long) filter.getOrDefault("fromBlock", currentBlock);
    final long toBlock = (Long) filter.getOrDefault("toBlock", currentBlock);

    if (fromBlock > toBlock) {
      throw new GraphQLException(GraphQLError.INVALID_PARAMS);
    }

    @SuppressWarnings("unchecked")
    final List<Address> addrs = (List<Address>) filter.get("addresses");
    @SuppressWarnings("unchecked")
    final List<List<Bytes32>> topics = (List<List<Bytes32>>) filter.get("topics");

    final List<List<LogTopic>> transformedTopics = new ArrayList<>();
    for (final List<Bytes32> topic : topics) {
      transformedTopics.add(topic.stream().map(LogTopic::of).collect(Collectors.toList()));
    }

    final LogsQuery query =
        new LogsQuery.Builder().addresses(addrs).topics(transformedTopics).build();

    final List<LogWithMetadata> logs =
        blockchainQuery.matchingLogs(
            fromBlock, toBlock, query, dataFetcherContext.getIsAliveHandler());
    final List<LogAdapter> results = new ArrayList<>();
    for (final LogWithMetadata log : logs) {
      results.add(new LogAdapter(log));
    }
    return Optional.of(results);
  };
}
 
Example #19
Source Project: besu   Author: hyperledger   File: GraphQLDataFetchers.java    License: Apache License 2.0 5 votes vote down vote up
DataFetcher<Optional<TransactionAdapter>> getTransactionDataFetcher() {
  return dataFetchingEnvironment -> {
    final BlockchainQueries blockchain =
        ((GraphQLDataFetcherContext) dataFetchingEnvironment.getContext()).getBlockchainQueries();
    final Bytes32 hash = dataFetchingEnvironment.getArgument("hash");
    final Optional<TransactionWithMetadata> tran = blockchain.transactionByHash(Hash.wrap(hash));
    return tran.map(TransactionAdapter::new);
  };
}
 
Example #20
Source Project: camel-quarkus   Author: apache   File: GraphQLResource.java    License: Apache License 2.0 5 votes vote down vote up
public void setupRouter(@Observes Router router) {
    SchemaParser schemaParser = new SchemaParser();
    final TypeDefinitionRegistry typeDefinitionRegistry;
    try (Reader r = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("graphql/schema.graphql"),
            StandardCharsets.UTF_8)) {
        typeDefinitionRegistry = schemaParser.parse(r);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    DataFetcher<CompletionStage<Book>> dataFetcher = environment -> {
        CompletableFuture<Book> completableFuture = new CompletableFuture<>();
        Book book = getBookById(environment);
        completableFuture.complete(book);
        return completableFuture;
    };

    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder -> builder.dataFetcher("bookById", dataFetcher))
            .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

    router.route("/graphql/server").handler(GraphQLHandler.create(graphQL));
}
 
Example #21
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<String> idFetcher() {
    
    return environment -> {
        RDFNode thisNode = environment.getSource();

        if (thisNode.asResource().isURIResource()) {
            return thisNode.asResource().getURI();
        } else {
            return "_:" + thisNode.asNode().getBlankNodeLabel();
        }
    };
}
 
Example #22
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<List<RDFNode>> instancesOfTypeFetcher() {
    return environment -> {
        Field field = (Field) environment.getFields().toArray()[0];
        String predicate = (field.getAlias() == null) ? field.getName() : field.getAlias();
        ModelContainer client = environment.getContext();
        return client.getValuesOfObjectProperty(
                HGQLVocabulary.HGQL_QUERY_URI,
                HGQLVocabulary.HGQL_QUERY_NAMESPACE + predicate
        );
    };
}
 
Example #23
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<RDFNode> objectFetcher() {
    return environment -> {
        FetchParams params = new FetchParams(environment, schema);
        return params.getClient().getValueOfObjectProperty(
                params.getSubjectResource(),
                params.getPredicateURI(),
                params.getTargetURI()
        );
    };
}
 
Example #24
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<List<RDFNode>> objectsFetcher() {
    return environment -> {
        FetchParams params = new FetchParams(environment, schema);
        return params.getClient().getValuesOfObjectProperty(
                params.getSubjectResource(),
                params.getPredicateURI(),
                params.getTargetURI()
        );
    };
}
 
Example #25
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<String> literalValueFetcher() {
    return environment -> {
        FetchParams params = new FetchParams(environment, schema);
        return params.getClient().getValueOfDataProperty(
                params.getSubjectResource(),
                params.getPredicateURI(),
                environment.getArguments()
        );
    };
}
 
Example #26
Source Project: hypergraphql   Author: hypergraphql   File: FetcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public DataFetcher<List<String>> literalValuesFetcher() {
    return environment -> {
        FetchParams params = new FetchParams(environment, schema);
        return params.getClient().getValuesOfDataProperty(
                params.getSubjectResource(),
                params.getPredicateURI(),
                environment.getArguments()
        );
    };
}
 
Example #27
Source Project: hypergraphql   Author: hypergraphql   File: HGQLSchemaWiring.java    License: Apache License 2.0 5 votes vote down vote up
private GraphQLFieldDefinition getBuiltQueryField(FieldOfTypeConfig field, DataFetcher fetcher) {

        List<GraphQLArgument> args = new ArrayList<>();

        if (this.hgqlSchema.getQueryFields().get(field.getName()).type().equals(HGQL_QUERY_GET_FIELD)) {
            args.addAll(getQueryArgs);
        } else {
            args.addAll(getByIdQueryArgs);
        }

        final QueryFieldConfig queryFieldConfig = this.hgqlSchema.getQueryFields().get(field.getName());

        Service service = queryFieldConfig.service();
        if(service == null) {
            throw new HGQLConfigurationException("Service for field '" + field.getName() + "':['"
                    + queryFieldConfig.type() + "'] not specified (null)");
        }
        String serviceId = service.getId();
        String description = (queryFieldConfig.type().equals(HGQL_QUERY_GET_FIELD)) ?
                "Get instances of " + field.getTargetName() + " (service: " + serviceId + ")" :
                "Get instances of " + field.getTargetName() + " by URIs (service: " + serviceId + ")";

        return newFieldDefinition()
                .name(field.getName())
                .argument(args)
                .description(description)
                .type(field.getGraphqlOutputType())
                .dataFetcher(fetcher)
                .build();
    }
 
Example #28
Source Project: graphql-java-examples   Author: graphql-java   File: StockTickerGraphqlPublisher.java    License: MIT License 5 votes vote down vote up
private DataFetcher stockQuotesSubscriptionFetcher() {
    return environment -> {
        List<String> arg = environment.getArgument("stockCodes");
        List<String> stockCodesFilter = arg == null ? Collections.emptyList() : arg;
        if (stockCodesFilter.isEmpty()) {
            return STOCK_TICKER_PUBLISHER.getPublisher();
        } else {
            return STOCK_TICKER_PUBLISHER.getPublisher(stockCodesFilter);
        }
    };
}
 
Example #29
Source Project: rejoiner   Author: google   File: GuavaListenableFutureSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
 *
 * <p>{@see CompletableFuture} is supported by the provided {@link
 * graphql.execution.AsyncExecutionStrategy}.
 *
 * <p>Note: This should be installed before any other instrumentation.
 */
public static Instrumentation listenableFutureInstrumentation(Executor executor) {
  return new SimpleInstrumentation() {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
        DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
      return (DataFetcher<Object>)
          dataFetchingEnvironment -> {
            Object data = dataFetcher.get(dataFetchingEnvironment);
            if (data instanceof ListenableFuture) {
              ListenableFuture<Object> listenableFuture = (ListenableFuture<Object>) data;
              CompletableFuture<Object> completableFuture = new CompletableFuture<>();
              Futures.addCallback(
                  listenableFuture,
                  new FutureCallback<Object>() {
                    @Override
                    public void onSuccess(Object result) {
                      completableFuture.complete(result);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                      completableFuture.completeExceptionally(t);
                    }
                  },
                  executor);
              return completableFuture;
            }
            return data;
          };
    }
  };
}
 
Example #30
Source Project: rejoiner   Author: google   File: ProtoToGql.java    License: Apache License 2.0 5 votes vote down vote up
private static GraphQLFieldDefinition convertField(
    FieldDescriptor fieldDescriptor, SchemaOptions schemaOptions) {
  DataFetcher<?> dataFetcher = new ProtoDataFetcher(fieldDescriptor);
  GraphQLFieldDefinition.Builder builder =
      newFieldDefinition()
          .type(convertType(fieldDescriptor, schemaOptions))
          .dataFetcher(dataFetcher)
          .name(fieldDescriptor.getJsonName());
  builder.description(schemaOptions.commentsMap().get(fieldDescriptor.getFullName()));
  if (fieldDescriptor.getOptions().hasDeprecated()
      && fieldDescriptor.getOptions().getDeprecated()) {
    builder.deprecate("deprecated in proto");
  }
  return builder.build();
}