graphql.language.Field Java Examples

The following examples show how to use graphql.language.Field. 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: ComplexityAnalyzer.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private ResolvedField collectFields(FieldCollectorParameters parameters, List<ResolvedField> fields) {
    ResolvedField field = fields.get(0);
    if (!fields.stream().allMatch(f -> f.getFieldType() instanceof GraphQLFieldsContainer)) {
        field.setComplexityScore(complexityFunction.getComplexity(field, 0));
        return field;
    }
    List<Field> rawFields = fields.stream().map(ResolvedField::getField).collect(Collectors.toList());
    Map<String, ResolvedField> children = collectFields(parameters, rawFields, (GraphQLFieldsContainer) field.getFieldType());
    ResolvedField node = new ResolvedField(field.getField(), field.getFieldDefinition(), field.getArguments(), children);
    int childScore = children.values().stream().mapToInt(ResolvedField::getComplexityScore).sum();
    int complexityScore = complexityFunction.getComplexity(node, childScore);
    if (complexityScore > maximumComplexity) {
        throw new ComplexityLimitExceededException(complexityScore, maximumComplexity);
    }
    node.setComplexityScore(complexityScore);
    return node;
}
 
Example #2
Source File: SelectorToFieldMask.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Builder getFieldMaskForProto(
    DataFetchingEnvironment environment, Descriptor descriptor, String startAtFieldName) {

  Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName();

  Builder maskFromSelectionBuilder = FieldMask.newBuilder();

  for (Field field : environment.getFields()) {
    for (Selection<?> selection1 : field.getSelectionSet().getSelections()) {
      if (selection1 instanceof Field) {
        Field field2 = (Field) selection1;
        if (field2.getName().equals(startAtFieldName)) {
          for (Selection<?> selection : field2.getSelectionSet().getSelections()) {
            maskFromSelectionBuilder.addAllPaths(
                getPathsForProto("", selection, descriptor, fragmentsByName));
          }
        }
      }
    }
  }
  return maskFromSelectionBuilder;
}
 
Example #3
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldIgnoreSelectorsNotInProto() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field("username"),
                                              new Field("notInPersonProto")))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("username").build());
}
 
Example #4
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("schema must not have empty config")
void schema_must_have_config_2() {

    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);
    when(environment.getFields()).thenReturn(Collections.singletonList(mock(Field.class)));

    HGQLSchema schema = mock(HGQLSchema.class);
    when(schema.getFields()).thenReturn(Collections.emptyMap());

    Executable executable = () -> new FetchParams(
            environment,
            schema
    );
    assertThrows(NullPointerException.class, executable);
}
 
Example #5
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("schema must have config for predicate")
void schema_must_have_config_for_predicate() {

    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);
    Field field = mock(Field.class);
    when(environment.getFields()).thenReturn(Collections.singletonList(field));
    when(field.getName()).thenReturn("field1");

    HGQLSchema schema = mock(HGQLSchema.class);
    FieldConfig fieldConfig = mock(FieldConfig.class);
    when(schema.getFields()).thenReturn(Collections.singletonMap("field", fieldConfig));

    Executable executable = () -> new FetchParams(
            environment,
            schema
    );
    assertThrows(NullPointerException.class, executable);
}
 
Example #6
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnNestedField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(new Field("month"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("birthday.month").build());
}
 
Example #7
Source File: RxExecutionStrategy.java    From graphql-rxjava with MIT License 6 votes vote down vote up
@Override
protected ExecutionResult completeValueForList(ExecutionContext executionContext, GraphQLList fieldType, List<Field> fields, List<Object> result) {
    Observable<?> resultObservable =
            Observable.from(
                    IntStream.range(0, result.size())
                            .mapToObj(idx -> new ListTuple(idx, result.get(idx)))
                            .toArray(ListTuple[]::new)
            )
            .flatMap(tuple -> {
                ExecutionResult executionResult = completeValue(executionContext, fieldType.getWrappedType(), fields, tuple.result);

                if (executionResult instanceof RxExecutionResult) {
                    return Observable.zip(Observable.just(tuple.index), ((RxExecutionResult)executionResult).getDataObservable(), ListTuple::new);
                }
                return Observable.just(new ListTuple(tuple.index, executionResult.getData()));
            })
            .toList()
            .map(listTuples -> {
                return listTuples.stream()
                        .sorted(Comparator.comparingInt(x -> x.index))
                        .map(x -> x.result)
                        .collect(Collectors.toList());
            });

    return new RxExecutionResult(resultObservable, null);
}
 
Example #8
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method support to extracted nested level operations
 * @param selectionList selection List
 * @param supportedFields supportedFields
 * @param operationArray operationArray
 */
public void getNestedLevelOperations(List<Selection> selectionList, ArrayList<String> supportedFields,
                            ArrayList<String> operationArray) {
    for (Selection selection : selectionList) {
        Field levelField = (Field) selection;
        if (!operationArray.contains(levelField.getName()) &&
                supportedFields.contains(levelField.getName())) {
            operationArray.add(levelField.getName());
            if (log.isDebugEnabled()) {
                log.debug("Extracted operation: " + levelField.getName());
            }
        }
        if (levelField.getSelectionSet() != null) {
            getNestedLevelOperations(levelField.getSelectionSet().getSelections(), supportedFields, operationArray);
        }
    }
}
 
Example #9
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnMultipleNestedField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(
                                                          new Field("day"),
                                                          new Field("month"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(
          FieldMask.newBuilder().addPaths("birthday.day").addPaths("birthday.month").build());
}
 
Example #10
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldFallbackToStarPathIfSubSelectorNameDoesntMatchProto() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "birthday",
                                                  new SelectionSet(
                                                      ImmutableList.of(new Field("unknown"))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("birthday.*").build());
}
 
Example #11
Source File: ExecutionTreeNode.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
ExecutionTreeNode(Field field, String nodeId , HGQLSchema schema ) {

        if(schema.getQueryFields().containsKey(field.getName())) {
            this.service = schema.getQueryFields().get(field.getName()).service();
        } else if(schema.getFields().containsKey(field.getName())) {
            LOGGER.info("here");
        } else {
            throw new HGQLConfigurationException("Field '" + field.getName() + "' not found in schema");
        }
        this.executionId = createId();
        this.childrenNodes = new HashMap<>();
        this.ldContext = new HashMap<>();
        this.ldContext.putAll(HGQLVocabulary.JSONLD);
        this.rootType = "Query";
        this.hgqlSchema = schema;
        this.query = getFieldJson(field, null, nodeId, "Query");
    }
 
Example #12
Source File: MockDataFetchEnvironment.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
public static DataFetchingEnvironment myFastQueryDfe(String typeName, String fieldName, String operationName,
        String executionId) {
    GraphQLNamedType query = mock(GraphQLNamedType.class);
    when(query.getName()).thenReturn(typeName);

    Field field = mock(Field.class);
    when(field.getName()).thenReturn(fieldName);

    OperationDefinition operationDefinition = mock(OperationDefinition.class);
    when(operationDefinition.getName()).thenReturn(operationName);

    ExecutionPath executionPath = mock(ExecutionPath.class);
    when(executionPath.toString()).thenReturn("/" + typeName + "/" + fieldName);
    ExecutionStepInfo executionStepInfo = mock(ExecutionStepInfo.class);
    when(executionStepInfo.getPath()).thenReturn(executionPath);

    DataFetchingEnvironment dfe = mock(DataFetchingEnvironment.class);
    when(dfe.getParentType()).thenReturn(query);
    when(dfe.getField()).thenReturn(field);
    when(dfe.getOperationDefinition()).thenReturn(operationDefinition);
    when(dfe.getExecutionStepInfo()).thenReturn(executionStepInfo);
    when(dfe.getExecutionId()).thenReturn(ExecutionId.from(executionId));

    return dfe;
}
 
Example #13
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Environment parent type must have a name")
void environment_must_have_parent_type_name() {

    HGQLSchema schema = mock(HGQLSchema.class);
    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);

    Field field1 = mock(Field.class);

    List<Field> fields = Collections.singletonList(field1);
    when(environment.getFields()).thenReturn(fields);
    when(field1.getName()).thenReturn("field1");

    FieldConfig fieldConfig = mock(FieldConfig.class);
    Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
    when(schema.getFields()).thenReturn(schemaFields);

    GraphQLType parentType = mock(GraphQLType.class);
    when(environment.getParentType()).thenReturn(parentType);

    Executable executable = () -> new FetchParams(environment, schema);
    assertThrows(NullPointerException.class, executable);
}
 
Example #14
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Environment must have a parent type")
void environment_must_have_parent_type() {

    String uri = "abc123";

    HGQLSchema schema = mock(HGQLSchema.class);
    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);

    Field field1 = mock(Field.class);

    List<Field> fields = Collections.singletonList(field1);
    when(environment.getFields()).thenReturn(fields);
    when(field1.getName()).thenReturn("field1");

    FieldConfig fieldConfig = mock(FieldConfig.class);
    Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
    when(schema.getFields()).thenReturn(schemaFields);

    when(fieldConfig.getId()).thenReturn(uri);

    Executable executable = () -> new FetchParams(environment, schema);
    assertThrows(NullPointerException.class, executable);
}
 
Example #15
Source File: SelectorToFieldMask.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Builder getFieldMaskForProto(
    DataFetchingEnvironment environment, Descriptor descriptor) {

  Map<String, FragmentDefinition> fragmentsByName = environment.getFragmentsByName();

  Builder maskFromSelectionBuilder = FieldMask.newBuilder();
  for (Field field :
      Optional.ofNullable(environment.getMergedField())
          .map(MergedField::getFields)
          .orElse(ImmutableList.of())) {
    for (Selection<?> selection : field.getSelectionSet().getSelections()) {
      maskFromSelectionBuilder.addAllPaths(
          getPathsForProto("", selection, descriptor, fragmentsByName));
    }
  }
  return maskFromSelectionBuilder;
}
 
Example #16
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void getFieldMaskForProtoShouldReturnSingleField() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field",
                                      new SelectionSet(ImmutableList.of(new Field("username")))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor())
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("username").build());
}
 
Example #17
Source File: ResolvedField.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public ResolvedField(Field field, GraphQLFieldDefinition fieldDefinition, Map<String, Object> arguments, Map<String, ResolvedField> children) {
    this.name = field.getAlias() != null ? field.getAlias() : field.getName();
    this.field = field;
    this.fieldDefinition = fieldDefinition;
    this.fieldType = (GraphQLOutputType) GraphQLUtils.unwrap(fieldDefinition.getType());
    this.arguments = arguments;
    this.children = children;
    this.resolver = findResolver(fieldDefinition, arguments);
}
 
Example #18
Source File: RxExecutionStrategy.java    From graphql-rxjava with MIT License 5 votes vote down vote up
@Override
protected ExecutionResult completeValue(ExecutionContext executionContext, GraphQLType fieldType, List<Field> fields, Object result) {
    if (result instanceof Observable) {
        return new RxExecutionResult(((Observable<?>) result).map(r -> super.completeValue(executionContext, fieldType, fields, r)), null);
    }
    return super.completeValue(executionContext, fieldType, fields, result);
}
 
Example #19
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("schema must have some config")
void schema_must_have_config() {

    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);
    when(environment.getFields()).thenReturn(Collections.singletonList(mock(Field.class)));

    Executable executable = () -> new FetchParams(
            environment,
            mock(HGQLSchema.class)
    );
    assertThrows(NullPointerException.class, executable);
}
 
Example #20
Source File: ComplexityAnalyzer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
/**
 * Given a list of fields this will collect the sub-field selections and return it as a map
 *
 * @param parameters the parameters to this method
 * @param fields     the list of fields to collect for
 *
 * @return a map of the sub field selections
 */
private Map<String, ResolvedField> collectFields(FieldCollectorParameters parameters, List<Field> fields, GraphQLFieldsContainer parent) {
    List<String> visitedFragments = new ArrayList<>();
    Map<String, List<ResolvedField>> unconditionalSubFields = new LinkedHashMap<>();
    Map<String, Map<String, List<ResolvedField>>> conditionalSubFields = new LinkedHashMap<>();

    fields.stream()
            .filter(field -> field.getSelectionSet() != null)
            .forEach(field -> collectFields(parameters, unconditionalSubFields, getUnconditionalSelections(field.getSelectionSet()), visitedFragments, parent));

    fields.stream()
            .filter(field -> field.getSelectionSet() != null)
            .forEach(field ->
                    getConditionalSelections(field.getSelectionSet()).forEach((condition, selections) -> {
                                Map<String, List<ResolvedField>> subFields = new LinkedHashMap<>();
                                collectFields(parameters, subFields, selections, visitedFragments, parent);
                                conditionalSubFields.put(condition, subFields);
                            }
                    ));

    if (conditionalSubFields.isEmpty()) {
        return unconditionalSubFields.values().stream()
                .map(nodes -> collectFields(parameters, nodes))
                .collect(Collectors.toMap(ResolvedField::getName, Function.identity()));
    } else {
        return reduceAlternatives(parameters, unconditionalSubFields, conditionalSubFields);
    }
}
 
Example #21
Source File: ExtendedJpaDataFetcher.java    From graphql-jpa with MIT License 5 votes vote down vote up
@Override
public Object get(DataFetchingEnvironment environment) {
    Field field = environment.getFields().iterator().next();
    Map<String, Object> result = new LinkedHashMap<>();

    PageInformation pageInformation = extractPageInformation(environment, field);

    // See which fields we're requesting
    Optional<Field> totalPagesSelection = getSelectionField(field, "totalPages");
    Optional<Field> totalElementsSelection = getSelectionField(field, "totalElements");
    Optional<Field> contentSelection = getSelectionField(field, "content");

    if (contentSelection.isPresent())
        result.put("content", getQuery(environment, contentSelection.get()).setMaxResults(pageInformation.size).setFirstResult((pageInformation.page - 1) * pageInformation.size).getResultList());

    if (totalElementsSelection.isPresent() || totalPagesSelection.isPresent()) {
        final Long totalElements = contentSelection
                .map(contentField -> getCountQuery(environment, contentField).getSingleResult())
                // if no "content" was selected an empty Field can be used
                .orElseGet(() -> getCountQuery(environment, new Field()).getSingleResult());

        result.put("totalElements", totalElements);
        result.put("totalPages", ((Double) Math.ceil(totalElements / (double) pageInformation.size)).longValue());
    }

    return result;
}
 
Example #22
Source File: ComplexityAnalyzer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
ResolvedField collectFields(ExecutionContext context) {
    FieldCollectorParameters parameters = FieldCollectorParameters.newParameters()
            .schema(context.getGraphQLSchema())
            .objectType(context.getGraphQLSchema().getQueryType())
            .fragments(context.getFragmentsByName())
            .variables(context.getVariables())
            .build();
    List<Field> fields = context.getOperationDefinition().getSelectionSet().getSelections().stream()
            .map(selection -> (Field) selection)
            .collect(Collectors.toList());

    Map<String, ResolvedField> roots = fields.stream()
            .map(field -> {
                GraphQLFieldDefinition fieldDefinition;
                if (GraphQLUtils.isIntrospectionField(field)) {
                    fieldDefinition = Introspection.SchemaMetaFieldDef;
                } else {
                    fieldDefinition = Objects.requireNonNull(
                            getRootType(context.getGraphQLSchema(), context.getOperationDefinition())
                                    .getFieldDefinition(field.getName()));
                }

                Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldDefinition.getArguments(), field.getArguments(), context.getVariables());
                return collectFields(parameters, Collections.singletonList(new ResolvedField(field, fieldDefinition, argumentValues)));
            })
            .collect(Collectors.toMap(ResolvedField::getName, Function.identity()));

    ResolvedField root = new ResolvedField(roots);
    if (root.getComplexityScore() > maximumComplexity) {
        throw new ComplexityLimitExceededException(root.getComplexityScore(), maximumComplexity);
    }
    return root;
}
 
Example #23
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 #24
Source File: RxExecutionStrategy.java    From graphql-rxjava with MIT License 5 votes vote down vote up
@Override
public ExecutionResult execute(ExecutionContext executionContext, GraphQLObjectType parentType, Object source, Map<String, List<Field>> fields) {

    List<Observable<Pair<String, ?>>> observables = new ArrayList<>();
    for (String fieldName : fields.keySet()) {
        final List<Field> fieldList = fields.get(fieldName);

        ExecutionResult executionResult = resolveField(executionContext, parentType, source, fieldList);

        if (executionResult instanceof RxExecutionResult) {
            RxExecutionResult rxResult = (RxExecutionResult)executionResult;
            Observable<?> unwrapped = rxResult.getDataObservable().flatMap(potentialResult -> {
                if (potentialResult instanceof RxExecutionResult) {
                    return ((RxExecutionResult) potentialResult).getDataObservable();
                }

                if (potentialResult instanceof ExecutionResult) {
                    return Observable.just(((ExecutionResult) potentialResult).getData());
                }

                return Observable.just(potentialResult);
            });

            observables.add(Observable.zip(Observable.just(fieldName), unwrapped, Pair::of));
        } else {
            observables.add(Observable.just(Pair.of(fieldName, executionResult != null ? executionResult.getData() : null)));
        }
    }

    Observable<Map<String, Object>> result =
            Observable.merge(observables)
                    .toMap(Pair::getLeft, Pair::getRight);

    return new RxExecutionResult(result, Observable.just(executionContext.getErrors()));
}
 
Example #25
Source File: UsernameFieldValidation.java    From notification with Apache License 2.0 5 votes vote down vote up
@Override
public List<GraphQLError> validateFields(FieldValidationEnvironment environment) {
  final List<GraphQLError> errors = new ArrayList<>();

  for (FieldAndArguments fieldAndArguments : environment.getFields()) {
    final Field field = fieldAndArguments.getField();
    if (!VALID_FIELDS.contains(field.getName())) {
      continue;
    }

    LOGGER.debug("Field: {}", field.getName());

    final String username = fieldAndArguments.getArgumentValue("username");

    if (Strings.isNullOrEmpty(username)) {
      errors.add(environment.mkError("username cannot be empty", fieldAndArguments));
    } else {
      final int length = username.codePointCount(0, username.length());

      if (length < USERNAME_MIN_LENGTH || length > USERNAME_MAX_LENGTH) {
        errors.add(
            environment.mkError(
                String.format(
                    "username must be between %d and %d characters",
                    USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH),
                fieldAndArguments));
      } else if (!username.matches("[A-Za-z0-9]+")) {
        errors.add(
            environment.mkError(
                "username must only contain alphanumeric characters", fieldAndArguments));
      }
    }
  }

  return errors;
}
 
Example #26
Source File: ComplexityAnalyzer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private void collectField(FieldCollectorParameters parameters, Map<String, List<ResolvedField>> fields, Field field, GraphQLFieldsContainer parent) {
    if (!conditionalNodes.shouldInclude(parameters.getVariables(), field.getDirectives())) {
        return;
    }
    GraphQLFieldDefinition fieldDefinition = parent.getFieldDefinition(field.getName());
    Map<String, Object> argumentValues = valuesResolver.getArgumentValues(fieldDefinition.getArguments(), field.getArguments(), parameters.getVariables());
    ResolvedField node = new ResolvedField(field, fieldDefinition, argumentValues);
    fields.putIfAbsent(node.getName(), new ArrayList<>());
    fields.get(node.getName()).add(node);
}
 
Example #27
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Happy path for a non-Query type with no target")
void happy_path_non_query_type_with_no_target() {

    String uri = "abc123";

    HGQLSchema schema = mock(HGQLSchema.class);
    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);

    Field field1 = mock(Field.class);

    List<Field> fields = Collections.singletonList(field1);
    when(environment.getFields()).thenReturn(fields);
    when(field1.getName()).thenReturn("field1");

    FieldConfig fieldConfig = mock(FieldConfig.class);
    Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
    when(schema.getFields()).thenReturn(schemaFields);

    when(fieldConfig.getId()).thenReturn(uri);

    GraphQLType parent = mock(GraphQLType.class);
    when(environment.getParentType()).thenReturn(parent);
    when(parent.getName()).thenReturn("non-Query");

    TypeConfig typeConfig = mock(TypeConfig.class);
    Map<String, TypeConfig> types = Collections.singletonMap("non-Query", typeConfig);
    when(schema.getTypes()).thenReturn(types);
    FieldOfTypeConfig fieldOfTypeConfig = mock(FieldOfTypeConfig.class);
    when(typeConfig.getField("field1")).thenReturn(fieldOfTypeConfig);
    when(fieldOfTypeConfig.getTargetName()).thenReturn("non-Query");

    when(typeConfig.getId()).thenReturn("targetUri");

    FetchParams fetchParams = new FetchParams(environment, schema);

    assertNotNull(fetchParams);
    assertEquals(uri, fetchParams.getPredicateURI());
    assertEquals("targetUri", fetchParams.getTargetURI());
}
 
Example #28
Source File: FetchParamsTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Happy path for a Query type")
void happy_path_query_config() {

    String uri = "abc123";

    HGQLSchema schema = mock(HGQLSchema.class);
    DataFetchingEnvironment environment = mock(DataFetchingEnvironment.class);

    Field field1 = mock(Field.class);

    List<Field> fields = Collections.singletonList(field1);
    when(environment.getFields()).thenReturn(fields);
    when(field1.getName()).thenReturn("field1");

    FieldConfig fieldConfig = mock(FieldConfig.class);
    Map<String, FieldConfig> schemaFields = Collections.singletonMap("field1", fieldConfig);
    when(schema.getFields()).thenReturn(schemaFields);

    when(fieldConfig.getId()).thenReturn(uri);

    GraphQLType parent = mock(GraphQLType.class);
    when(environment.getParentType()).thenReturn(parent);
    when(parent.getName()).thenReturn("Query");

    FetchParams fetchParams = new FetchParams(environment, schema);

    assertNotNull(fetchParams);
    assertEquals(uri, fetchParams.getPredicateURI());
}
 
Example #29
Source File: FetchParams.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
public FetchParams(DataFetchingEnvironment environment, HGQLSchema hgqlschema) {

        subjectResource = environment.getSource();
        String predicate = ((Field) environment.getFields().toArray()[0]).getName();
        predicateURI = hgqlschema.getFields().get(predicate).getId();
        client = environment.getContext();
        if (!environment.getParentType().getName().equals("Query")) {
            String targetName = hgqlschema.getTypes().get(environment.getParentType().getName()).getField(predicate).getTargetName();
            if (hgqlschema.getTypes().containsKey(targetName) && hgqlschema.getTypes().get(targetName).getId()!=null) {
                targetURI=hgqlschema.getTypes().get(targetName).getId();
            }
        }
    }
 
Example #30
Source File: SelectorToFieldMaskTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void getFieldMaskForChildProto() {
  assertThat(
          SelectorToFieldMask.getFieldMaskForProto(
                  DataFetchingEnvironmentImpl.newDataFetchingEnvironment()
                      .mergedField(
                          MergedField.newMergedField()
                              .addField(
                                  new Field(
                                      "top_level_field", // QueryType
                                      new SelectionSet(
                                          ImmutableList.of(
                                              new Field(
                                                  "second_level_field", // RequestType
                                                  new SelectionSet(
                                                      ImmutableList.of(
                                                          new Field(
                                                              "birthday",
                                                              new SelectionSet(
                                                                  ImmutableList.of(
                                                                      new Field("month")))))))))))
                              .build())
                      .build(),
                 PersonOuterClass.Person.getDescriptor(),
                  "second_level_field")
              .build())
      .isEqualTo(FieldMask.newBuilder().addPaths("birthday.month").build());
}