graphql.schema.GraphQLFieldDefinition Java Examples

The following examples show how to use graphql.schema.GraphQLFieldDefinition. 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: SchemaProviderModuleTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void schemaModuleShouldProvideQueryType() {
  Injector injector =
      Guice.createInjector(
          new SchemaProviderModule(),
          new SchemaModule() {
            @Query
            GraphQLFieldDefinition greeting =
                GraphQLFieldDefinition.newFieldDefinition()
                    .name("greeting")
                    .type(Scalars.GraphQLString)
                    .staticValue("hello world")
                    .build();
          });
  assertThat(
          injector
              .getInstance(Key.get(GraphQLSchema.class, Schema.class))
              .getQueryType()
              .getFieldDefinition("greeting"))
      .isNotNull();
}
 
Example #2
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addMutations(GraphQLSchema.Builder schemaBuilder) {

        if (schema.hasMutations()) {
            GraphQLObjectType.Builder mutationBuilder = GraphQLObjectType.newObject()
                    .name(MUTATION)
                    .description("Mutation root");

            Set<Operation> mutations = schema.getMutations();
            for (Operation mutationOperation : mutations) {
                GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(MUTATION,
                        mutationOperation);
                mutationBuilder = mutationBuilder.field(graphQLFieldDefinition);
            }

            GraphQLObjectType mutation = mutationBuilder.build();
            if (mutation.getFieldDefinitions() != null && !mutation.getFieldDefinitions().isEmpty()) {
                schemaBuilder.mutation(mutation);
            }
        }
    }
 
Example #3
Source File: OptionalsTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapping() {
    GraphQLFieldDefinition intQuery = schema.getQueryType().getFieldDefinition("int");
    GraphQLFieldDefinition longQuery = schema.getQueryType().getFieldDefinition("long");
    GraphQLFieldDefinition doubleQuery = schema.getQueryType().getFieldDefinition("double");
    GraphQLFieldDefinition stringQuery = schema.getQueryType().getFieldDefinition("string");
    GraphQLFieldDefinition nestedQuery = schema.getQueryType().getFieldDefinition("nested");
    assertEquals(Scalars.GraphQLInt, intQuery.getType());
    assertEquals(Scalars.GraphQLInt, intQuery.getArgument("opt").getType());
    assertEquals(Scalars.GraphQLLong, longQuery.getType());
    assertEquals(Scalars.GraphQLLong, longQuery.getArgument("opt").getType());
    assertEquals(Scalars.GraphQLFloat, doubleQuery.getType());
    assertEquals(Scalars.GraphQLFloat, doubleQuery.getArgument("opt").getType());
    assertEquals(Scalars.GraphQLString, stringQuery.getType());
    assertEquals(Scalars.GraphQLString, stringQuery.getArgument("opt").getType());
    assertEquals(Scalars.GraphQLString, nestedQuery.getType());
    assertEquals(Scalars.GraphQLString, nestedQuery.getArgument("opt").getType());
}
 
Example #4
Source File: SchemaDefinition.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
protected SchemaDefinition(GraphQLSchema schema, SchemaMetadata metadata) {
    this.schema = schema;
    this.schemaMetadata = metadata == null ? SchemaMetadata.create() : metadata;
    this.schemaName = schemaMetadata.getSchemaName() == null || schemaMetadata.getSchemaName().isEmpty() ?
            schema.getQueryType().getName() : schemaMetadata.getSchemaName();
    this.serviceAddress = schemaMetadata.getServiceAddress() == null ||
            schemaMetadata.getServiceAddress().isEmpty() ?
                    Queryable.ADDRESS_PREFIX + "." + schemaName() : schemaMetadata.getServiceAddress();

    schemaMetadata.put(SchemaMetadata.METADATA_QUERIES, schema.getQueryType().getFieldDefinitions().stream()
            .map(GraphQLFieldDefinition::getName).collect(Collectors.toList()));
    schemaMetadata.put(SchemaMetadata.METADATA_MUTATIONS,
            !schema.isSupportingMutations() ? Collections.emptyList() :
                    schema.getMutationType().getFieldDefinitions().stream()
                            .map(GraphQLFieldDefinition::getName).collect(Collectors.toList()));
}
 
Example #5
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtendedPageMapping() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new ExtendedPageBookService())
            .generate();

    GraphQLFieldDefinition totalCount = schema.getObjectType("BookConnection")
            .getFieldDefinition("totalCount");
    assertNotNull(totalCount);
    assertNonNull(totalCount.getType(), Scalars.GraphQLLong);
    GraphQL exe = GraphQLRuntime.newGraphQL(schema).build();

    ExecutionResult result = exe.execute("{extended(first:10, after:\"20\") {" +
            "   totalCount" +
            "   pageInfo {" +
            "       hasNextPage" +
            "   }," +
            "   edges {" +
            "       cursor, node {" +
            "           title" +
            "}}}}");
    assertNoErrors(result);
    assertValueAtPathEquals(100L, result, "extended.totalCount");
    assertValueAtPathEquals("Tesseract", result, "extended.edges.0.node.title");
}
 
Example #6
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition createGraphQLFieldDefinitionFromField(String ownerName, Field field) {
    GraphQLFieldDefinition.Builder fieldBuilder = GraphQLFieldDefinition.newFieldDefinition()
            .name(field.getName())
            .description(field.getDescription());

    // Type
    fieldBuilder = fieldBuilder.type(createGraphQLOutputType(field));

    GraphQLFieldDefinition graphQLFieldDefinition = fieldBuilder.build();

    // DataFetcher
    PropertyDataFetcher datafetcher = new PropertyDataFetcher(field);
    codeRegistryBuilder.dataFetcher(FieldCoordinates.coordinates(ownerName,
            graphQLFieldDefinition.getName()), datafetcher);

    return graphQLFieldDefinition;
}
 
Example #7
Source File: SchemaBundleTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void createSchemaUsingSchemaBundle() {
  final SchemaBundle.Builder schemaBuilder = SchemaBundle.builder();
  schemaBuilder
      .modificationsBuilder()
      .add(
          Type.find("inner")
              .addField(
                  GraphQLFieldDefinition.newFieldDefinition()
                      .name("bazinga")
                      .type(Scalars.GraphQLBigInteger)
                      .build()));
  schemaBuilder
      .queryFieldsBuilder()
      .add(
          GraphQLFieldDefinition.newFieldDefinition()
              .name("bazinga")
              .type(GraphQLObjectType.newObject().name("inner"))
              .build());
  final SchemaBundle schemaBundle = schemaBuilder.build();
  final GraphQLSchema schema = schemaBundle.toSchema();
  assertThat(schema.getQueryType().getFieldDefinitions()).hasSize(1);
  assertThat(schema.getQueryType().getFieldDefinitions().get(0).getName()).isEqualTo("bazinga");
}
 
Example #8
Source File: RelayImpl.java    From glitr with MIT License 6 votes vote down vote up
@Override
public GraphQLObjectType connectionType(String name, GraphQLObjectType edgeType, List<GraphQLFieldDefinition> connectionFields) {
    return newObject()
            .name(name + "Connection")
            .description("A connection to a list of items.")
            .field(newFieldDefinition()
                    .name("edges")
                    .type(new GraphQLConnectionList(edgeType))
                    .build())
            .field(newFieldDefinition()
                    .name("pageInfo")
                    .type(new GraphQLNonNull(pageInfoType))
                    .definition(new GlitrFieldDefinition(name, Sets.newHashSet(new GlitrMetaDefinition(COMPLEXITY_IGNORE_KEY, true))))
                    .build())
            .fields(connectionFields)
            .build();
}
 
Example #9
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLObjectType registerGraphQLQueryType(TypeConfig type) {

        String typeName = type.getName();
        String description = "Top queryable predicates. " +
                "_GET queries return all objects of a given type, possibly restricted by limit and offset values. " +
                "_GET_BY_ID queries require a set of URIs to be specified.";

        List<GraphQLFieldDefinition> builtFields;

        Map<String, FieldOfTypeConfig> fields = type.getFields();

        Set<String> fieldNames = fields.keySet();

        builtFields = fieldNames.stream()
                .map(fieldName -> registerGraphQLQueryField(type.getField(fieldName)))
                .collect(Collectors.toList());

        return newObject()
                .name(typeName)
                .description(description)
                .fields(builtFields)
                .build();
    }
 
Example #10
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition registerGraphQLField(FieldOfTypeConfig field) {
    FetcherFactory fetcherFactory = new FetcherFactory(hgqlSchema);

    Boolean isList = field.isList();

    if (SCALAR_TYPES.containsKey(field.getTargetName())) {
        if (isList) {
            return getBuiltField(field, fetcherFactory.literalValuesFetcher());
        } else {
            return getBuiltField(field, fetcherFactory.literalValueFetcher());
        }

    } else {
        if (isList) {
            return getBuiltField(field, fetcherFactory.objectsFetcher());
        } else {
            return getBuiltField(field, fetcherFactory.objectFetcher());
        }
    }
}
 
Example #11
Source File: PrimitivesTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void nonNullBooleanVoidTest() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new BooleanVoidService())
            .generate();
    GraphQLObjectType query = schema.getQueryType();
    GraphQLFieldDefinition field;

    field = query.getFieldDefinition("primitiveVoid");
    assertNonNull(field.getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("objVoid");
    assertSame(field.getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("primitiveBoolean");
    assertNonNull(field.getType(), Scalars.GraphQLBoolean);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("objBoolean");
    assertSame(field.getType(), Scalars.GraphQLBoolean);
    assertSame(field.getArgument("in").getType(), Scalars.GraphQLBoolean);
}
 
Example #12
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 #13
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
protected GraphQLOutputType generateOutputType(Object object) {
    //An enum is a special case in both java and graphql,
    //and must be checked for while generating other kinds of types
    GraphQLEnumType enumType = generateEnumType(object);
    if (enumType != null) {
        return enumType;
    }
    
    List<GraphQLFieldDefinition> fields = getOutputFieldDefinitions(object);
    if (fields == null || fields.isEmpty()) {
        return null;
    }
    
    String typeName = getGraphQLTypeNameOrIdentityCode(object);
    GraphQLObjectType.Builder builder = newObject()
            .name(typeName)
            .fields(fields)
            .description(getTypeDescription(object));
    
    GraphQLInterfaceType[] interfaces = getInterfaces(object);
    if (interfaces != null) {
        builder.withInterfaces(interfaces);
    }
    return builder.build();
}
 
Example #14
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition registerGraphQLField(FieldOfTypeConfig field) {
    FetcherFactory fetcherFactory = new FetcherFactory(hgqlSchema);

    Boolean isList = field.isList();

    if (SCALAR_TYPES.containsKey(field.getTargetName())) {
        if (isList) {
            return getBuiltField(field, fetcherFactory.literalValuesFetcher());
        } else {
            return getBuiltField(field, fetcherFactory.literalValueFetcher());
        }

    } else {
        if (isList) {
            return getBuiltField(field, fetcherFactory.objectsFetcher());
        } else {
            return getBuiltField(field, fetcherFactory.objectFetcher());
        }
    }
}
 
Example #15
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("JdkObsolete")
static Set<GraphQLType> getAllTypes(GraphQLSchema schema) {
  LinkedHashSet<GraphQLType> types = new LinkedHashSet<>();
  LinkedList<GraphQLObjectType> loop = new LinkedList<>();
  loop.add(schema.getQueryType());
  types.add(schema.getQueryType());

  while (!loop.isEmpty()) {
    for (GraphQLFieldDefinition field : loop.pop().getFieldDefinitions()) {
      GraphQLType type = field.getType();
      if (type instanceof GraphQLList) {
        type = ((GraphQLList) type).getWrappedType();
      }
      if (!types.contains(type)) {
        if (type instanceof GraphQLEnumType) {
          types.add(field.getType());
        }
        if (type instanceof GraphQLObjectType) {
          types.add(type);
          loop.add((GraphQLObjectType) type);
        }
      }
    }
  }
  return types;
}
 
Example #16
Source File: TypeGeneratorParameterizedTest.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
public void basicsOutput() {
    GraphQLType type = generator.getOutputType(clazz);
    Assert.assertThat(type,
            instanceOf(GraphQLObjectType.class));
    GraphQLObjectType objectType = (GraphQLObjectType) type;
    Assert.assertThat(objectType.getName(),
            containsString(expectedName));
    Assert.assertThat(objectType.getDescription(),
            containsString("Autogenerated f"));
    Assert.assertThat(objectType.getFieldDefinitions(),
            notNullValue());
    for (GraphQLFieldDefinition field : objectType.getFieldDefinitions()) {
        Assert.assertThat(field,
                notNullValue());
        Assert.assertThat(field.getDescription(),
                containsString("Autogenerated f"));
    }
    Assert.assertThat(objectType.getFieldDefinitions().size(),
            is(expectedNumFields));
}
 
Example #17
Source File: DefaultTypeInfoGenerator.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public GraphqlTypeComparatorRegistry generateComparatorRegistry(AnnotatedType type, MessageBundle messageBundle) {
    if (!isOrdered(type)) {
        return DEFAULT_REGISTRY;
    }
    return new GraphqlTypeComparatorRegistry() {
        @Override
        public <T extends GraphQLSchemaElement> Comparator<? super T> getComparator(GraphqlTypeComparatorEnvironment env) {
            if (env.getElementType().equals(GraphQLFieldDefinition.class)) {
                return comparator(getFieldOrder(type, messageBundle), env);
            }
            if (env.getElementType().equals(GraphQLInputObjectField.class)
                    || env.getElementType().equals(GraphQLEnumValueDefinition.class)) {
                return comparator(getInputFieldOrder(type, messageBundle), env);
            }
            return DEFAULT_REGISTRY.getComparator(env);
        }
    };
}
 
Example #18
Source File: InterfaceMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public GraphQLInterfaceType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLInterfaceType.Builder typeBuilder = newInterface()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    List<GraphQLFieldDefinition> fields = objectTypeMapper.getFields(typeName, javaType, env);
    fields.forEach(typeBuilder::field);

    typeBuilder.withDirective(Directives.mappedType(javaType));
    buildContext.directiveBuilder.buildInterfaceTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            typeBuilder.withDirective(env.operationMapper.toGraphQLDirective(directive, buildContext)));
    typeBuilder.comparatorRegistry(buildContext.comparatorRegistry(javaType));
    GraphQLInterfaceType type = typeBuilder.build();
    buildContext.codeRegistry.typeResolver(type, buildContext.typeResolver);

    registerImplementations(javaType, type, env);
    return type;
}
 
Example #19
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLObjectType registerGraphQLQueryType(TypeConfig type) {

        String typeName = type.getName();
        String description = "Top queryable predicates. " +
                "_GET queries return all objects of a given type, possibly restricted by limit and offset values. " +
                "_GET_BY_ID queries require a set of URIs to be specified.";

        List<GraphQLFieldDefinition> builtFields = new ArrayList<>();

        Map<String, FieldOfTypeConfig> fields = type.getFields();

        Set<String> fieldNames = fields.keySet();

        for (String fieldName : fieldNames) {
            builtFields.add(registerGraphQLQueryField(type.getField(fieldName)));
        }

        return newObject()
                .name(typeName)
                .description(description)
                .fields(builtFields)
                .build();
    }
 
Example #20
Source File: PermissionBasedFieldVisibilityTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void getFieldDefinitionsShowsOnlyDataSetsThatUserHasAccessTo() throws Exception {
  final DataSetRepository dataSetRepository = mock(DataSetRepository.class);
  DataSet dataSet = createDataSetWithUserPermissions(
    "user__dataSetUserHasAccessTo",
    Sets.newHashSet(Permission.READ)
  );
  DataSet dataSet2 = createDataSetWithUserPermissions(
    "user__dataSetUserDoesNotHasAccessTo",
    Sets.newHashSet()
  );
  Collection<DataSet> dataSetCollection = Sets.newHashSet(dataSet, dataSet2);
  given(dataSetRepository.getDataSets()).willReturn(dataSetCollection);
  final PermissionBasedFieldVisibility permissionBasedFieldVisibility =
    new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository);
  final GraphQLFieldsContainer graphQlFieldsContainer = createGraphQlFieldsContainer(
    "user__dataSetUserHasAccessTo",
    "user__dataSetUserDoesNotHasAccessTo"
  );

  List<GraphQLFieldDefinition> retrievedGraphQlFieldDefinitions = permissionBasedFieldVisibility
    .getFieldDefinitions(graphQlFieldsContainer);

  assertThat(retrievedGraphQlFieldDefinitions, contains(hasProperty("name", is("user__dataSetUserHasAccessTo"))));
}
 
Example #21
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 #22
Source File: TypeTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void replaceFieldShouldReplaceField() throws Exception {
  TypeModification typeModification =
      Type.find("project")
          .replaceField(
              GraphQLFieldDefinition.newFieldDefinition()
                  .name("name")
                  .type(Scalars.GraphQLInt)
                  .build());
  assertThat(typeModification.apply(OBJECT_TYPE).getFieldDefinition("name").getType())
      .isEqualTo(Scalars.GraphQLInt);
}
 
Example #23
Source File: TypeGeneratorGenericsTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testGeneratedListOfParam() {
    logger.debug("testGeneratedListOfParam");
    Object objectType = generator.getOutputType(ClassWithListOfGenerics.class);
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition field = ((GraphQLObjectType) objectType)
            .getFieldDefinition("listOfParamOfInts");
    
    Assert.assertThat(field, notNullValue());
    GraphQLOutputType listType = field.getType();
    Assert.assertThat(listType, instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) listType).getWrappedType();
    Assert.assertThat(wrappedType, instanceOf(GraphQLObjectType.class));
}
 
Example #24
Source File: PrimitivesTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void nonNullIntTest() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new PrimitiveService())
            .generate();
    GraphQLObjectType query = schema.getQueryType();
    GraphQLFieldDefinition field;

    field = query.getFieldDefinition("primitive");
    assertNonNull(field.getType(), Scalars.GraphQLInt);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLInt);

    field = query.getFieldDefinition("primitiveWithDefault");
    assertNonNull(field.getType(), Scalars.GraphQLInt);
    assertSame(field.getArgument("in").getType(), Scalars.GraphQLInt);

    field = query.getFieldDefinition("nonNullPrimitive");
    assertNonNull(field.getType(), Scalars.GraphQLInt);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLInt);

    field = query.getFieldDefinition("relayIdPrimitive");
    assertSame(field.getType(), io.leangen.graphql.util.Scalars.RelayId);
    assertSame(field.getArgument(GraphQLId.RELAY_ID_FIELD_NAME).getType(), io.leangen.graphql.util.Scalars.RelayId);

    field = query.getFieldDefinition("nonNullInteger");
    assertNonNull(field.getType(), Scalars.GraphQLInt);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLInt);

    field = query.getFieldDefinition("integer");
    assertSame(field.getType(), Scalars.GraphQLInt);
    assertSame(field.getArgument("in").getType(), Scalars.GraphQLInt);
}
 
Example #25
Source File: UniquenessTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private void testRootQueryTypeUniqueness(GraphQLSchema schema) {
    List<GraphQLType> fieldTypes = schema.getQueryType().getFieldDefinitions().stream()
            .map(GraphQLFieldDefinition::getType)
            .map(GraphQLUtils::unwrap)
            .collect(Collectors.toList());
    assertEquals(2, fieldTypes.size());
    assertTrue(fieldTypes.stream().allMatch(type -> fieldTypes.get(0) == type));
}
 
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: TimeFieldFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    // Add the timezone field as text
    parentGraphQLType.field(GraphQLFieldDefinition.newFieldDefinition()
        .name(getGraphQLName(graphQLFieldName) + FIELD_SUFFIX_TZ)
        .description("Time Zone for field " + contentTypeFieldId)
        .type(GraphQLString)
        .argument(TEXT_FILTER));

    // Add the original according to the suffix
    setTypeFromFieldName(contentTypeFieldId, graphQLField);
}
 
Example #28
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private GraphQLFieldDefinition getidField() {
    FetcherFactory fetcherFactory = new FetcherFactory(hgqlSchema);

    return newFieldDefinition()
            .type(GraphQLID)
            .name("_id")
            .description("The URI of this resource.")
            .dataFetcher(fetcherFactory.idFetcher()).build();
}
 
Example #29
Source File: RepeatGroupFieldFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    // For Repeating Groups we need to create a wrapper type and do everything all over
    GraphQLObjectType.Builder repeatType = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEM)
        .description("Item for repeat group of " + contentTypeFieldId);

    List<Node> fields =
        XmlUtils.selectNodes(contentTypeField, fieldsXPath, Collections.emptyMap());

    // Call recursively for all fields in the repeating group
    if (CollectionUtils.isNotEmpty(fields)) {
        fields.forEach(f -> typeFactory.createField(contentTypeDefinition, f, parentGraphQLTypeName, repeatType));
    }

    GraphQLObjectType wrapperType = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEMS)
        .description("Wrapper for list of items of " + contentTypeFieldId)
        .field(GraphQLFieldDefinition.newFieldDefinition()
            .name(FIELD_NAME_ITEM)
            .description("List of items of " + contentTypeFieldId)
            .type(list(repeatType.build())))
        .build();

    graphQLField.type(wrapperType);
}
 
Example #30
Source File: MethodDataFetcher.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private GraphQLFieldDefinition getFieldType(GraphQLType type) {
    if ( type instanceof GraphQLFieldsContainer ) {
    		GraphQLFieldDefinition fieldType = ((GraphQLFieldsContainer)type).getFieldDefinition(propertyName);
    		
    		if (null == fieldType && null != this.graphQLPropertyName) {
    			fieldType = ((GraphQLFieldsContainer)type).getFieldDefinition(graphQLPropertyName);
    		}
    		
    		return fieldType;
    }
    return null;
}