graphql.schema.GraphQLScalarType Java Examples

The following examples show how to use graphql.schema.GraphQLScalarType. 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: FederationSdlPrinter.java    From federation-jvm with MIT License 6 votes vote down vote up
private TypePrinter<GraphQLScalarType> scalarPrinter() {
    return (out, type, visibility) -> {
        if (!options.isIncludeScalars()) {
            return;
        }
        boolean printScalar;
        if (ScalarInfo.isStandardScalar(type)) {
            printScalar = false;
            //noinspection RedundantIfStatement
            if (options.isIncludeExtendedScalars() && !ScalarInfo.isGraphqlSpecifiedScalar(type)) {
                printScalar = true;
            }
        } else {
            printScalar = true;
        }
        if (printScalar) {
            if (shouldPrintAsAst(type.getDefinition())) {
                printAsAst(out, type.getDefinition(), type.getExtensionDefinitions());
            } else {
                printComments(out, type, "");
                out.format("scalar %s%s\n\n", type.getName(), directivesString(GraphQLScalarType.class, type.getDirectives()));
            }
        }
    };
}
 
Example #2
Source File: JavaScriptEvaluator.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public int getComplexity(ResolvedField node, int childScore) {
    Resolver resolver = node.getResolver();
    if (resolver == null || Utils.isEmpty(resolver.getComplexityExpression())) {
        GraphQLType fieldType = node.getFieldType();
        if (fieldType instanceof GraphQLScalarType || fieldType instanceof GraphQLEnumType) {
            return 1;
        }
        if (GraphQLUtils.isRelayConnectionType(fieldType)) {
            Integer pageSize = getPageSize(node.getArguments());
            if (pageSize != null) {
                return pageSize * childScore;
            }
        }
        return 1 + childScore;
    }
    Bindings bindings = engine.createBindings();
    bindings.putAll(node.getArguments());
    bindings.put("childScore", childScore);
    try {
        return ((Number) engine.eval(resolver.getComplexityExpression(), bindings)).intValue();
    } catch (Exception e) {
        throw new IllegalArgumentException(String.format("Complexity expression \"%s\" on field %s could not be evaluated",
                resolver.getComplexityExpression(), node.getName()), e);
    }
}
 
Example #3
Source File: JacksonObjectScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static Map<Type, GraphQLScalarType> getScalarMapping() {
    Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
    scalarMapping.put(ObjectNode.class, JsonObjectNode);
    scalarMapping.put(POJONode.class, JsonObjectNode);
    scalarMapping.put(JsonNode.class, JsonAnyNode);
    return Collections.unmodifiableMap(scalarMapping);
}
 
Example #4
Source File: DefaultType_ReflectionScalarsLookup.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Override
public GraphQLType getDefaultType(Object object, TypeKind typeKind) {
    GraphQLScalarType scalar = getDefaultScalarType(object);
    if (scalar != null) return scalar;
    if (TypeKind.OBJECT.equals(typeKind)) {
        return getDefaultOutputType(object);
    }
    return null;
}
 
Example #5
Source File: TypeGeneratorListOfListTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
public static void assertListOfListOfInt(GraphQLType type) {
    Assert.assertThat(type, instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) type).getWrappedType();
    Assert.assertThat(wrappedType, instanceOf(GraphQLList.class));
    GraphQLType integerType = ((GraphQLList) wrappedType).getWrappedType();
    Assert.assertThat(integerType, instanceOf(GraphQLScalarType.class));
}
 
Example #6
Source File: TypeGeneratorScalarsTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testScalarsOutput() {
    logger.debug("testScalarsOutput {} {}", clazz, expected.getName());
    Assert.assertThat(generator.getOutputType(clazz),
            instanceOf(GraphQLScalarType.class));
    Assert.assertThat((GraphQLScalarType)generator.getOutputType(clazz),
            is(expected));
}
 
Example #7
Source File: TypeGeneratorScalarsTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testScalarsInput() {
    logger.debug("testScalarsInput {} {}", clazz, expected.getName());
    Assert.assertThat(generator.getInputType(clazz),
            instanceOf(GraphQLScalarType.class));
    Assert.assertThat((GraphQLScalarType)generator.getInputType(clazz),
            is(expected));
}
 
Example #8
Source File: TypeGeneratorRawArrayTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
public void assertListOfInt(Object objectType) {
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition fieldDefinition = ((GraphQLObjectType) objectType).getFieldDefinition("integers");
    Assert.assertThat(fieldDefinition, notNullValue());
    GraphQLOutputType outputType = fieldDefinition.getType();

    Assert.assertThat(outputType, CoreMatchers.instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) outputType).getWrappedType();
    Assert.assertThat(wrappedType, instanceOf(GraphQLScalarType.class));
    Assert.assertThat((GraphQLScalarType)wrappedType, is(Scalars.GraphQLInt));
}
 
Example #9
Source File: ObjectScalarMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLScalarType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLDirective[] directives = buildContext.directiveBuilder.buildScalarTypeDirectives(javaType, buildContext.directiveBuilderParams()).stream()
            .map(directive -> env.operationMapper.toGraphQLDirective(directive, buildContext))
            .toArray(GraphQLDirective[]::new);
    return ClassUtils.isSuperClass(Map.class, javaType)
            ? Scalars.graphQLMapScalar(typeName, directives)
            : Scalars.graphQLObjectScalar(typeName, directives);
}
 
Example #10
Source File: CachingMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private String getTypeName(AnnotatedType javaType, AnnotatedType graphQLType, TypeInfoGenerator typeInfoGenerator, MessageBundle messageBundle) {
    if (ClassUtils.isSuperClass(GraphQLScalarType.class, graphQLType)) {
        return typeInfoGenerator.generateScalarTypeName(javaType, messageBundle);
    }
    if (ClassUtils.isSuperClass(GraphQLEnumType.class, graphQLType)) {
        return typeInfoGenerator.generateEnumTypeName(javaType, messageBundle);
    }
    if (ClassUtils.isSuperClass(GraphQLInputType.class, graphQLType)) {
        return typeInfoGenerator.generateInputTypeName(javaType, messageBundle);
    }
    return typeInfoGenerator.generateTypeName(javaType, messageBundle);
}
 
Example #11
Source File: GsonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static Map<Type, GraphQLScalarType> getScalarMapping() {
    Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
    scalarMapping.put(JsonObject.class, JsonObjectNode);
    scalarMapping.put(JsonElement.class, JsonAnyNode);
    scalarMapping.put(JsonPrimitive.class, JsonPrimitiveNode);
    return Collections.unmodifiableMap(scalarMapping);
}
 
Example #12
Source File: JacksonObjectScalarMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLScalarType toGraphQLInputType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    if (POJONode.class.equals(javaType.getType())) {
        throw new UnsupportedOperationException(POJONode.class.getSimpleName() + " can not be used as input");
    }
    return toGraphQLType(javaType, mappersToSkip, env);
}
 
Example #13
Source File: Scalars.java    From besu with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType bigIntScalar() {
  return GraphQLScalarType.newScalar()
      .name("BigInt")
      .description("A BigInt (UInt256) scalar")
      .coercing(BIG_INT_COERCING)
      .build();
}
 
Example #14
Source File: JacksonScalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static Map<Type, GraphQLScalarType> getScalarMapping() {
    Map<Type, GraphQLScalarType> scalarMapping = new HashMap<>();
    scalarMapping.put(TextNode.class, JsonTextNode);
    scalarMapping.put(BooleanNode.class, JsonBooleanNode);
    scalarMapping.put(BinaryNode.class, JsonBinaryNode);
    scalarMapping.put(BigIntegerNode.class, JsonBigIntegerNode);
    scalarMapping.put(IntNode.class, JsonIntegerNode);
    scalarMapping.put(ShortNode.class, JsonShortNode);
    scalarMapping.put(DecimalNode.class, JsonDecimalNode);
    scalarMapping.put(FloatNode.class, JsonFloatNode);
    scalarMapping.put(DoubleNode.class, JsonDoubleNode);
    scalarMapping.put(NumericNode.class, JsonDecimalNode);
    return Collections.unmodifiableMap(scalarMapping);
}
 
Example #15
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType graphQLMapScalar(String name, GraphQLDirective[] directives) {
    return GraphQLScalarType.newScalar()
            .name(name)
            .description("Built-in scalar for map-like structures")
            .withDirectives(directives)
            .coercing(MAP_SCALAR_COERCION)
            .build();
}
 
Example #16
Source File: Scalars.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType graphQLObjectScalar(String name, GraphQLDirective[] directives) {
    return GraphQLScalarType.newScalar()
            .name(name)
            .description("Built-in scalar for dynamic values")
            .withDirectives(directives)
            .coercing(OBJECT_SCALAR_COERCION)
            .build();
}
 
Example #17
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 #18
Source File: TemporalScalarsTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private void testTemporalMapping(Class type, GraphQLScalarType scalar) {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withOperationsFromSingleton(new ScalarService(), TypeFactory.parameterizedClass(ScalarService.class, type))
            .generate();
    GraphQLFieldDefinition query = schema.getQueryType().getFieldDefinition("identity");
    assertEquals(scalar, query.getType());
    assertEquals(scalar, query.getArgument("input").getType());
}
 
Example #19
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 #20
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 5 votes vote down vote up
private Stream<GraphQLArgument> getArgument(Attribute attribute) {
    return getAttributeType(attribute)
            .filter(type -> type instanceof GraphQLInputType)
            .filter(type -> attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.EMBEDDED ||
                    (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED && type instanceof GraphQLScalarType))
            .map(type -> {
                String name = attribute.getName();                   

                return GraphQLArgument.newArgument()
                        .name(name)
                        .type((GraphQLInputType) type)
                        .build();
            });
}
 
Example #21
Source File: Scalars.java    From besu with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType addressScalar() {
  return GraphQLScalarType.newScalar()
      .name("Address")
      .description("Address scalar")
      .coercing(ADDRESS_COERCING)
      .build();
}
 
Example #22
Source File: GqlScalars.java    From manifold with Apache License 2.0 5 votes vote down vote up
public static Collection<GraphQLScalarType> transformFormatTypeResolvers()
{
  Set<GraphQLScalarType> scalars = new HashSet<>();
  for( IJsonFormatTypeCoercer formatCoercer: IJsonFormatTypeCoercer.get() )
  {
    formatCoercer.getFormats().forEach( (format, type) ->
      scalars.add( GraphQLScalarType.newScalar()
      .name( ManStringUtil.toPascalCase( format ) )
      .description( "Support values of type: " + type.getTypeName() )
      .coercing( makeCoercer( type, formatCoercer ) )
      .build() ) );
  }
  return scalars;
}
 
Example #23
Source File: Scalars.java    From besu with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType bytesScalar() {
  return GraphQLScalarType.newScalar()
      .name("Bytes")
      .description("A Bytes scalar")
      .coercing(BYTES_COERCING)
      .build();
}
 
Example #24
Source File: Scalars.java    From besu with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType bytes32Scalar() {
  return GraphQLScalarType.newScalar()
      .name("Bytes32")
      .description("A Bytes32 scalar")
      .coercing(BYTES32_COERCING)
      .build();
}
 
Example #25
Source File: Scalars.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
private static GraphQLScalarType scalar(String name, Coercing<?, ?> coercing) {
  return GraphQLScalarType
      .newScalar()
      .name(name)
      .description(name + " Scalar")
      .coercing(coercing)
      .build();
}
 
Example #26
Source File: FederationTest.java    From federation-jvm with MIT License 5 votes vote down vote up
@Test
void testPrinterFilter() {
    TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(printerFilterSDL);
    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Interface1", typeWiring -> typeWiring
                    .typeResolver(env -> null)
            )
            .type("Interface2", typeWiring -> typeWiring
                    .typeResolver(env -> null)
            )
            .scalar(GraphQLScalarType.newScalar()
                    .name("Scalar1")
                    .coercing(Scalars.GraphQLString.getCoercing())
                    .build()
            )
            .scalar(GraphQLScalarType.newScalar()
                    .name("Scalar2")
                    .coercing(Scalars.GraphQLString.getCoercing())
                    .build()
            )
            .build();
    GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(
            typeDefinitionRegistry,
            runtimeWiring
    );
    Assertions.assertEquals(
            printerFilterExpectedSDL.trim(),
            new FederationSdlPrinter(FederationSdlPrinter.Options.defaultOptions()
                    .includeScalarTypes(true)
                    .includeDirectiveDefinitions(def ->
                            !def.getName().endsWith("1") && !standardDirectives.contains(def.getName())
                    )
                    .includeTypeDefinitions(def -> !def.getName().endsWith("1"))
            ).print(graphQLSchema).trim()
    );
}
 
Example #27
Source File: Scalars.java    From besu with Apache License 2.0 5 votes vote down vote up
public static GraphQLScalarType longScalar() {
  return GraphQLScalarType.newScalar()
      .name("Long")
      .description("A Long (UInt64) scalar")
      .coercing(LONG_COERCING)
      .build();
}
 
Example #28
Source File: Scalars.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
/**
 * Returns null if not a scalar/primitive type
 * Otherwise returns an instance of GraphQLScalarType from Scalars.
 * @param clazz
 * @return
 */
public static GraphQLScalarType getScalarType(Class<?> clazz) {
    if (String.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLString;
    }
    if (Long.class.isAssignableFrom(clazz) || long.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLLong;
    }
    if (Integer.class.isAssignableFrom(clazz) || int.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLInt;
    }
    if (Double.class.isAssignableFrom(clazz) || double.class.isAssignableFrom(clazz)
            || Float.class.isAssignableFrom(clazz) || float.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLFloat;
    }
    if (Boolean.class.isAssignableFrom(clazz) || boolean.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLBoolean;
    }
    if (BigInteger.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLBigInteger;
    }
    if (BigDecimal.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLBigDecimal;
    }
    if (Byte.class.isAssignableFrom(clazz) || byte.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLByte;
    }
    if (Character.class.isAssignableFrom(clazz) || char.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLChar;
    }
    if (Short.class.isAssignableFrom(clazz) || short.class.isAssignableFrom(clazz)) {
        return graphql.Scalars.GraphQLShort;
    }
    return null;
}
 
Example #29
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 #30
Source File: TransformException.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private String getScalarTypeName() {
    GraphQLScalarType graphQLScalarType = GraphQLScalarTypes.getScalarMap().get(field.getReference().getClassName());
    if (graphQLScalarType != null) {
        return graphQLScalarType.getName();
    }
    return "Unknown Scalar Type [" + field.getReference().getClassName() + "]";
}