graphql.schema.GraphQLInputObjectType Java Examples

The following examples show how to use graphql.schema.GraphQLInputObjectType. 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: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void createGraphQLInputObjectType(InputType inputType) {
    GraphQLInputObjectType.Builder inputObjectTypeBuilder = GraphQLInputObjectType.newInputObject()
            .name(inputType.getName())
            .description(inputType.getDescription());

    // Fields
    if (inputType.hasFields()) {
        inputObjectTypeBuilder = inputObjectTypeBuilder
                .fields(createGraphQLInputObjectFieldsFromFields(inputType.getFields()));
        // Register this input for posible JsonB usage 
        JsonInputRegistry.register(inputType);
    }

    GraphQLInputObjectType graphQLInputObjectType = inputObjectTypeBuilder.build();
    inputMap.put(inputType.getClassName(), graphQLInputObjectType);
}
 
Example #2
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 #3
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
protected GraphQLInputType generateInputType(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<GraphQLInputObjectField> fields = getInputFieldDefinitions(object);
    if (fields == null || fields.isEmpty()) {
        return null;
    }
    String typeName = getGraphQLTypeNameOrIdentityCode(object);
    
    GraphQLInputObjectType.Builder builder = new GraphQLInputObjectType.Builder();
    builder.name(typeName);
    builder.fields(fields);
    builder.description(getTypeDescription(object));
    return builder.build();
}
 
Example #4
Source File: EnumMapToObjectTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLInputObjectType.Builder builder = GraphQLInputObjectType.newInputObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateInputTypeDescription(javaType, buildContext.messageBundle));

    @SuppressWarnings("rawtypes")
    Enum[] keys = (Enum[]) ClassUtils.getRawType(getElementType(javaType, 0).getType()).getEnumConstants();
    Arrays.stream(keys).forEach(enumValue -> {
        TypedElement element = new TypedElement(getElementType(javaType, 1), ClassUtils.getEnumConstantField(enumValue));
        builder.field(GraphQLInputObjectField.newInputObjectField()
                .name(enumMapper.getValueName(enumValue, buildContext.messageBundle))
                .description(enumMapper.getValueDescription(enumValue, buildContext.messageBundle))
                .type(env.forElement(element).toGraphQLInputType(element.getJavaType()))
                .build());
    });
    return builder.build();
}
 
Example #5
Source File: AnnotationMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLInputObjectType.Builder typeBuilder = newInputObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateInputTypeDescription(javaType, buildContext.messageBundle));

    InputFieldBuilderParams params = InputFieldBuilderParams.builder()
            .withType(javaType)
            .withEnvironment(buildContext.globalEnvironment)
            .build();
    buildContext.inputFieldBuilders.getInputFields(params).forEach(field -> typeBuilder.field(env.operationMapper.toGraphQLInputField(field, buildContext)));

    return typeBuilder.build();
}
 
Example #6
Source File: ObjectTypeMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLInputObjectType.Builder typeBuilder = newInputObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateInputTypeDescription(javaType, buildContext.messageBundle));

    InputFieldBuilderParams params = InputFieldBuilderParams.builder()
            .withType(javaType)
            .withEnvironment(buildContext.globalEnvironment)
            .withConcreteSubTypes(buildContext.abstractInputHandler.findConcreteSubTypes(ClassUtils.getRawType(javaType.getType()), buildContext))
            .build();
    buildContext.inputFieldBuilders.getInputFields(params).forEach(field -> typeBuilder.field(env.operationMapper.toGraphQLInputField(field, buildContext)));
    if (ClassUtils.isAbstract(javaType)) {
        createInputDisambiguatorField(javaType, buildContext).ifPresent(typeBuilder::field);
    }

    typeBuilder.withDirective(Directives.mappedType(javaType));
    buildContext.directiveBuilder.buildInputObjectTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            typeBuilder.withDirective(env.operationMapper.toGraphQLDirective(directive, buildContext)));
    typeBuilder.comparatorRegistry(buildContext.comparatorRegistry(javaType));

    return typeBuilder.build();
}
 
Example #7
Source File: TypeGeneratorParameterizedTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
public void basicsInput() {
    if (expectedToSucceed == false) {
        try {
            generator.getInputType(clazz);
            fail("Should have caught exception");
        }
        catch (Exception e) {
            Assert.assertThat(e, instanceOf(RuntimeException.class));
        }
        return;
    }
    
    GraphQLType type = generator.getInputType(clazz);
    Assert.assertThat(type,
            instanceOf(GraphQLInputObjectType.class));
    GraphQLInputObjectType objectType = (GraphQLInputObjectType) type;
    Assert.assertThat(objectType.getName(),
            containsString(expectedName));
    Assert.assertThat(objectType.getDescription(),
            containsString("Autogenerated f"));
    Assert.assertThat(objectType.getFields(),
            notNullValue());
    for (GraphQLInputObjectField field : objectType.getFields()) {
        Assert.assertThat(field,
                notNullValue());
        Assert.assertThat(field.getDescription(),
                containsString("Autogenerated f"));
    }
    Assert.assertThat(objectType.getFields().size(),
            is(expectedNumFields));
}
 
Example #8
Source File: PolymorphicJsonTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnambiguousAbstractType() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new VehicleService())
            .withAbstractInputTypeResolution()
            .withValueMapperFactory(valueMapperFactory)
            .generate();
    assertNull(((GraphQLInputObjectType) schema.getType("VehicleInput")).getFieldDefinition("_type_"));
    GraphQL exe = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = exe.execute("{ vehicle(in: {mode: \"flying\"}) {mode}}");
    assertTrue(result.getErrors().toString(), result.getErrors().isEmpty());
    assertValueAtPathEquals("flying", result, "vehicle.mode");
}
 
Example #9
Source File: GraphQLTypeAssertions.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static void assertInputMapOf(GraphQLType mapType, Class<? extends GraphQLType> keyType, Class<? extends GraphQLType> valueType) {
    assertEquals(GraphQLList.class, mapType.getClass());
    GraphQLType entry = GraphQLUtils.unwrap(mapType);
    assertTrue(entry instanceof GraphQLInputObjectType);
    GraphQLInputType key = ((GraphQLInputObjectType) entry).getFieldDefinition("key").getType();
    GraphQLInputType value = ((GraphQLInputObjectType) entry).getFieldDefinition("value").getType();
    assertTrue(keyType.isAssignableFrom(key.getClass()));
    assertTrue(valueType.isAssignableFrom(value.getClass()));
}
 
Example #10
Source File: DirectiveTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private void assertDirective(GraphQLDirectiveContainer container, String directiveName, String innerName) {
    Optional<graphql.schema.GraphQLArgument> argument = DirectivesUtil.directiveWithArg(container.getDirectives(), directiveName, "value");
    assertTrue(argument.isPresent());
    GraphQLInputObjectType argType = (GraphQLInputObjectType) GraphQLUtils.unwrapNonNull(argument.get().getType());
    assertEquals("WrapperInput", argType.getName());
    assertSame(Scalars.GraphQLString, argType.getFieldDefinition("name").getType());
    assertSame(Scalars.GraphQLString, argType.getFieldDefinition("value").getType());
    Wrapper wrapper = (Wrapper) argument.get().getValue();
    assertEquals(innerName, wrapper.name());
    assertEquals("test", wrapper.value());
}
 
Example #11
Source File: DirectiveTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchemaDirectives() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new ServiceWithDirectives())
            .generate();

    GraphQLFieldDefinition scalarField = schema.getQueryType().getFieldDefinition("scalar");
    assertDirective(scalarField, "fieldDef", "fieldDef");

    GraphQLScalarType scalarResult = (GraphQLScalarType) scalarField.getType();
    assertDirective(scalarResult, "scalar", "scalar");

    graphql.schema.GraphQLArgument argument = scalarField.getArgument("in");
    assertDirective(argument, "argDef", "argument");

    GraphQLInputObjectType inputType = (GraphQLInputObjectType) argument.getType();
    assertDirective(inputType, "inputObjectType", "input");
    graphql.schema.GraphQLArgument directiveArg = DirectivesUtil.directiveWithArg(inputType.getDirectives(), "inputObjectType", "value").get();
    Optional<graphql.schema.GraphQLArgument> metaArg = DirectivesUtil.directiveWithArg(directiveArg.getDirectives(), "meta", "value");
    assertTrue(metaArg.isPresent());
    assertEquals("meta", metaArg.get().getValue());

    GraphQLInputObjectField inputField = inputType.getField("value");
    assertDirective(inputField, "inputFieldDef", "inputField");

    GraphQLFieldDefinition objField = schema.getQueryType().getFieldDefinition("obj");
    GraphQLObjectType objResult = (GraphQLObjectType) objField.getType();
    assertDirective(objResult, "objectType", "object");

    GraphQLFieldDefinition innerField = objResult.getFieldDefinition("value");
    assertDirective(innerField, "fieldDef", "field");
}
 
Example #12
Source File: GenericsTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingGenerics() {
    Type type = TypeFactory.parameterizedClass(EchoService.class, MissingGenerics.class);
    GraphQLSchema schema = new TestSchemaGenerator()
            .withValueMapperFactory(valueMapperFactory)
            .withOperationsFromSingleton(new EchoService(), type, new PublicResolverBuilder())
            .withTypeTransformer(new DefaultTypeTransformer(true, true))
            .withTypeAdapters(new MapToListTypeAdapter())
            .generate();

    GraphQLFieldDefinition query = schema.getQueryType().getFieldDefinition("echo");
    GraphQLObjectType output = (GraphQLObjectType) query.getType();
    assertMapOf(output.getFieldDefinition("raw").getType(), GraphQLScalarType.class, GraphQLScalarType.class);
    assertMapOf(output.getFieldDefinition("unbounded").getType(), GraphQLScalarType.class, GraphQLScalarType.class);

    GraphQLInputObjectType input = (GraphQLInputObjectType) query.getArgument("in").getType();
    assertInputMapOf(input.getFieldDefinition("raw").getType(), GraphQLScalarType.class, GraphQLScalarType.class);
    assertInputMapOf(input.getFieldDefinition("unbounded").getType(), GraphQLScalarType.class, GraphQLScalarType.class);

    GraphQL runtime = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = runtime.execute("{" +
            "echo (in: {" +
            "   raw: [{key: 2, value: 3}]" +
            "   unbounded: [{key: 2, value: 3}]" +
            "}) {" +
            "   raw {key, value}" +
            "   unbounded {key, value}" +
            "}}");
    assertNoErrors(result);
    assertValueAtPathEquals(2, result, "echo.raw.0.key");
    assertValueAtPathEquals(3, result, "echo.raw.0.value");
    assertValueAtPathEquals(2, result, "echo.unbounded.0.key");
    assertValueAtPathEquals(3, result, "echo.unbounded.0.value");
}
 
Example #13
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
public FederationSdlPrinter(Options options) {
    this.options = options;
    printers.put(GraphQLSchema.class, schemaPrinter());
    printers.put(GraphQLObjectType.class, objectPrinter());
    printers.put(GraphQLEnumType.class, enumPrinter());
    printers.put(GraphQLScalarType.class, scalarPrinter());
    printers.put(GraphQLInterfaceType.class, interfacePrinter());
    printers.put(GraphQLUnionType.class, unionPrinter());
    printers.put(GraphQLInputObjectType.class, inputObjectPrinter());
}
 
Example #14
Source File: GqlInputConverterTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void inputConverterShouldCreateInputTypeWithCamelCaseName() {
  GqlInputConverter inputConverter =
      GqlInputConverter.newBuilder().add(TestProto.getDescriptor().getFile()).build();
  GraphQLInputObjectType input =
      (GraphQLInputObjectType)
          inputConverter.getInputType(Proto1.getDescriptor(), SchemaOptions.defaultOptions());
  Truth.assertThat(input.getField("intField")).isNotNull();
  Truth.assertThat(input.getField("camelCaseName")).isNotNull();
}
 
Example #15
Source File: RangeDirective.java    From samples with MIT License 5 votes vote down vote up
private boolean appliesTo(GraphQLFieldDefinition fieldDefinition) {
  return fieldDefinition.getArguments().stream().anyMatch(it -> {
    if (appliesTo(it)) {
      return true;
    }
    GraphQLInputType unwrappedInputType = Util.unwrapNonNull(it.getType());
    if (unwrappedInputType instanceof GraphQLInputObjectType) {
      GraphQLInputObjectType inputObjType = (GraphQLInputObjectType) unwrappedInputType;
      return inputObjType.getFieldDefinitions().stream().anyMatch(this::appliesTo);
    }
    return false;
  });
}
 
Example #16
Source File: DirectivesAndTypeWalker.java    From samples with MIT License 5 votes vote down vote up
private static boolean walkInputType(GraphQLInputType inputType, List<GraphQLDirective> directives, BiFunction<GraphQLInputType, GraphQLDirective, Boolean> isSuitable) {
  GraphQLInputType unwrappedInputType = Util.unwrapNonNull(inputType);
  for (GraphQLDirective directive : directives) {
    if (isSuitable.apply(unwrappedInputType, directive)) {
      return true;
    }
  }
  if (unwrappedInputType instanceof GraphQLInputObjectType) {
    GraphQLInputObjectType inputObjType = (GraphQLInputObjectType) unwrappedInputType;
    for (GraphQLInputObjectField inputField : inputObjType.getFieldDefinitions()) {
      inputType = inputField.getType();
      directives = inputField.getDirectives();

      if (walkInputType(inputType, directives, isSuitable)) {
        return true;
      }
    }
  }
  if (unwrappedInputType instanceof GraphQLList) {
    GraphQLInputType innerListType = Util.unwrapOneAndAllNonNull(unwrappedInputType);
    if (innerListType instanceof GraphQLDirectiveContainer) {
      directives = ((GraphQLDirectiveContainer) innerListType).getDirectives();
      if (walkInputType(innerListType, directives, isSuitable)) {
        return true;
      }
    }
  }
  return false;
}
 
Example #17
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private TypePrinter<GraphQLInputObjectType> inputObjectPrinter() {
    return (out, type, visibility) -> {
        if (isIntrospectionType(type)) {
            return;
        }
        if (shouldPrintAsAst(type.getDefinition())) {
            printAsAst(out, type.getDefinition(), type.getExtensionDefinitions());
        } else {
            printComments(out, type, "");
            GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
                    .parentType(GraphQLInputObjectType.class)
                    .elementType(GraphQLInputObjectField.class)
                    .build();
            Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment);

            out.format("input %s%s", type.getName(), directivesString(GraphQLInputObjectType.class, type.getDirectives()));
            List<GraphQLInputObjectField> inputObjectFields = visibility.getFieldDefinitions(type);
            if (inputObjectFields.size() > 0) {
                out.format(" {\n");
                inputObjectFields
                        .stream()
                        .sorted(comparator)
                        .forEach(fd -> {
                            printComments(out, fd, "  ");
                            out.format("  %s: %s",
                                    fd.getName(), typeString(fd.getType()));
                            Object defaultValue = fd.getDefaultValue();
                            if (defaultValue != null) {
                                String astValue = printAst(defaultValue, fd.getType());
                                out.format(" = %s", astValue);
                            }
                            out.format(directivesString(GraphQLInputObjectField.class, fd.getDirectives()));
                            out.format("\n");
                        });
                out.format("}");
            }
            out.format("\n\n");
        }
    };
}
 
Example #18
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
/**
 * This can print an in memory GraphQL schema back to a logical schema definition
 *
 * @param schema the schema in play
 * @return the logical schema definition
 */
public String print(GraphQLSchema schema) {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);

    GraphqlFieldVisibility visibility = schema.getCodeRegistry().getFieldVisibility();

    printer(schema.getClass()).print(out, schema, visibility);

    List<GraphQLType> typesAsList = schema.getAllTypesAsList()
            .stream()
            .sorted(Comparator.comparing(GraphQLNamedType::getName))
            .filter(options.getIncludeTypeDefinition())
            .collect(toList());

    printType(out, typesAsList, GraphQLInterfaceType.class, visibility);
    printType(out, typesAsList, GraphQLUnionType.class, visibility);
    printType(out, typesAsList, GraphQLObjectType.class, visibility);
    printType(out, typesAsList, GraphQLEnumType.class, visibility);
    printType(out, typesAsList, GraphQLScalarType.class, visibility);
    printType(out, typesAsList, GraphQLInputObjectType.class, visibility);

    String result = sw.toString();
    if (result.endsWith("\n\n")) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}
 
Example #19
Source File: InterfaceMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLInputObjectType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    return objectTypeMapper.toGraphQLInputType(typeName, javaType, env);
}