Java Code Examples for graphql.schema.GraphQLScalarType

The following examples show how to use graphql.schema.GraphQLScalarType. These examples are extracted from open source projects. 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 Project: federation-jvm   Author: apollographql   File: FederationSdlPrinter.java    License: 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 Project: graphql-spqr   Author: leangen   File: JavaScriptEvaluator.java    License: 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 Project: besu   Author: hyperledger   File: Scalars.java    License: 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 #4
Source Project: besu   Author: hyperledger   File: Scalars.java    License: 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 #5
Source Project: besu   Author: hyperledger   File: Scalars.java    License: 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 #6
Source Project: besu   Author: hyperledger   File: Scalars.java    License: 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 #7
Source Project: besu   Author: hyperledger   File: Scalars.java    License: 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 #8
Source Project: federation-jvm   Author: apollographql   File: FederationSdlPrinter.java    License: 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 #9
Source Project: federation-jvm   Author: apollographql   File: FederationSdlPrinter.java    License: 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 #10
Source Project: federation-jvm   Author: apollographql   File: FederationTest.java    License: 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 #11
Source Project: smallrye-graphql   Author: smallrye   File: TransformException.java    License: 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() + "]";
}
 
Example #12
Source Project: stream-registry   Author: ExpediaGroup   File: Scalars.java    License: 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 #13
Source Project: manifold   Author: manifold-systems   File: GqlScalars.java    License: 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 #14
Source Project: graphql-java-type-generator   Author: graphql-java   File: Scalars.java    License: 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 #15
Source Project: graphql-java-type-generator   Author: graphql-java   File: DefaultType_ReflectionScalarsLookup.java    License: 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 #16
Source Project: graphql-java-type-generator   Author: graphql-java   File: TypeGeneratorListOfListTest.java    License: 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 #17
Source Project: graphql-java-type-generator   Author: graphql-java   File: TypeGeneratorScalarsTest.java    License: 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 #18
Source Project: graphql-java-type-generator   Author: graphql-java   File: TypeGeneratorScalarsTest.java    License: 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 #19
Source Project: graphql-java-type-generator   Author: graphql-java   File: TypeGeneratorRawArrayTest.java    License: 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 #20
Source Project: graphql-spqr   Author: leangen   File: ObjectScalarMapper.java    License: 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 #21
Source Project: graphql-spqr   Author: leangen   File: CachingMapper.java    License: 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 #22
Source Project: graphql-spqr   Author: leangen   File: GsonScalars.java    License: 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 #23
Source Project: graphql-spqr   Author: leangen   File: JacksonObjectScalarMapper.java    License: 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 #24
Source Project: graphql-spqr   Author: leangen   File: JacksonObjectScalars.java    License: 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 #25
Source Project: graphql-spqr   Author: leangen   File: JacksonScalars.java    License: 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 #26
Source Project: graphql-spqr   Author: leangen   File: Scalars.java    License: 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 #27
Source Project: graphql-spqr   Author: leangen   File: Scalars.java    License: 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 #28
Source Project: graphql-spqr   Author: leangen   File: GenericsTest.java    License: 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 #29
Source Project: graphql-spqr   Author: leangen   File: TemporalScalarsTest.java    License: 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 #30
Source Project: graphql-spqr   Author: leangen   File: DirectiveTest.java    License: 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");
}