graphql.schema.DataFetcher Java Examples

The following examples show how to use graphql.schema.DataFetcher. 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 File: GraphQLDataFetchers.java    From besu with 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 File: GraphQLDataFetchers.java    From besu with 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 File: GraphQLExamples.java    From vertx-web with 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 #4
Source File: JsonResultsTest.java    From vertx-web with 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 #5
Source File: ResolverDataFetcher.java    From graphql-apigen with 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 #6
Source File: OperationMapper.java    From graphql-spqr with 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 #7
Source File: EnumMapToObjectTypeAdapter.java    From graphql-spqr with 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 #8
Source File: HGQLSchemaWiring.java    From hypergraphql with 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 #9
Source File: HGQLSchemaWiring.java    From hypergraphql with 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 File: UppercaseDirective.java    From samples with 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 #11
Source File: RangeDirective.java    From samples with 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 #12
Source File: FuturesConverter.java    From rejoiner with 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 #13
Source File: GraphQLDataFetchers.java    From rsocket-rpc-java with 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 #14
Source File: GraphQLDataFetchers.java    From rsocket-rpc-java with 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 #15
Source File: DroidsData.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static DataFetcher getFriendsDataFetcher() {
    return environment -> {
        List<Object> result = Collections.emptyList();
        List<String> friends = (List<String>) ((Map<String, Object>) environment.getSource()).get("friends");
        result.addAll(friends.stream().map(DroidsData::getCharacter).collect(Collectors.toList()));
        return result;
    };
}
 
Example #16
Source File: FetcherFactory.java    From hypergraphql with 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 #17
Source File: FetcherFactory.java    From hypergraphql with 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 #18
Source File: FieldsGenerator.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
/**
 * May return null should this field be disallowed
 * @param object
 * @return
 */
protected GraphQLFieldDefinition.Builder getOutputFieldDefinition(
        final Object object) {
    String fieldName = getFieldName(object);
    GraphQLOutputType fieldType = (GraphQLOutputType)
            getTypeOfField(object, TypeKind.OBJECT);
    if (fieldName == null || fieldType == null) {
        return null;
    }
    Object fieldFetcher = getFieldFetcher(object);
    String fieldDescription  = getFieldDescription(object);
    String fieldDeprecation  = getFieldDeprecation(object);
    List<GraphQLArgument> fieldArguments  = getFieldArguments(object);
    logger.debug("GraphQL field will be of type [{}] and name [{}] and fetcher [{}] with description [{}]",
            fieldType, fieldName, fieldFetcher, fieldDescription);
    
    GraphQLFieldDefinition.Builder fieldBuilder = newFieldDefinition()
            .name(fieldName)
            .type(fieldType)
            .description(fieldDescription)
            .deprecate(fieldDeprecation);
    if (fieldArguments != null) {
        fieldBuilder.argument(fieldArguments);
    }
    if (fieldFetcher instanceof DataFetcher) {
        fieldBuilder.dataFetcher((DataFetcher)fieldFetcher);
    }
    else if (fieldFetcher != null) {
        fieldBuilder.staticValue(fieldFetcher);
    }
    return fieldBuilder;
}
 
Example #19
Source File: HumanData.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static DataFetcher getFriendsDataFetcher() {
    return environment -> {
        List<Object> result = Collections.emptyList();
        List<String> friends = (List<String>) ((Map<String, Object>) environment.getSource()).get("friends");
        result.addAll(friends.stream().map(HumanData::getCharacter).collect(Collectors.toList()));
        return result;
    };
}
 
Example #20
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a generic resolver for the given operation.
 * @implSpec This resolver simply invokes {@link OperationExecutor#execute(DataFetchingEnvironment)}
 *
 * @param operation The operation for which the resolver is being created
 * @param buildContext The shared context containing all the global information needed for mapping
 *
 * @return The resolver for the given operation
 */
@SuppressWarnings("deprecation")
private DataFetcher<?> createResolver(Operation operation, BuildContext buildContext) {
    Stream<AnnotatedType> inputTypes = operation.getArguments().stream()
            .filter(OperationArgument::isMappable)
            .map(OperationArgument::getJavaType);
    ValueMapper valueMapper = buildContext.createValueMapper(inputTypes);

    if (operation.isBatched()) {
        return (BatchedDataFetcher) environment -> new OperationExecutor(operation, valueMapper, buildContext.globalEnvironment, buildContext.interceptorFactory).execute(environment);
    }
    return new OperationExecutor(operation, valueMapper, buildContext.globalEnvironment, buildContext.interceptorFactory)::execute;
}
 
Example #21
Source File: CompositeDataFetcherFactory.java    From glitr with MIT License 5 votes vote down vote up
public static DataFetcher create(final List<DataFetcher> supplied) {

        List<DataFetcher> fetchers = supplied.stream()
                // filter out all the OverrideDataFetchers that have a null overrideMethod since type registry adds a default overrideDF
                .filter(f -> !(f instanceof OverrideDataFetcher) || ((OverrideDataFetcher)f).getOverrideMethod() != null)
                .collect(Collectors.toList());

        return new CompositeDataFetcher(fetchers);
    }
 
Example #22
Source File: HGQLSchemaWiring.java    From hypergraphql with 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 '" + 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 #23
Source File: DroidsData.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
static DataFetcher getHeroDataFetcher() {
    return environment -> {
        if (environment.containsArgument("episode")
                && 5 == (int) environment.getArgument("episode")) return threepio; // It was Luke, but not here :-)
        return artoo;
    };
}
 
Example #24
Source File: FetcherFactory.java    From hypergraphql with 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 #25
Source File: FetcherFactory.java    From hypergraphql with 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 #26
Source File: StockTickerGraphqlPublisher.java    From graphql-java-subscription-example with 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 #27
Source File: ProtoToGql.java    From rejoiner with 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();
}
 
Example #28
Source File: GuavaListenableFutureSupport.java    From rejoiner with 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 #29
Source File: AbstractCompositeDataFetcher.java    From glitr with MIT License 5 votes vote down vote up
@Override
public Object get(DataFetchingEnvironment environment) throws Exception {
    for (DataFetcher fetcher : fetchers) {
        Object result = fetcher.get(environment);
        if (result != null) {
            return result;
        }
    }
    return null;
}
 
Example #30
Source File: FetcherFactory.java    From hypergraphql with 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();
        }
    };
}