Custom Scalar in Graphql-java

16.4k views Asked by At

We are planning use Graphql as backend server in our application. We choose Graphql-Java to develop our POC. We came across a stituation to create our own scalartype to handle java.util.Map object type.

we havent found any documentation regarding creating a custom scalar type. In example code as below

RuntimeWiring buildRuntimeWiring() {
    return RuntimeWiring.newRuntimeWiring()
            .scalar(CustomScalar)

how to was the implementation done for CustomScalar object. need help.

3

There are 3 answers

9
kaqqao On BEST ANSWER

To get a general idea how to make a scalar, just take a look into the existing ones and do something similar.

graphql-java also has a separate project for extra scalars: graphql-java-extended-scalars. And there you can find the object scalar (a.k.a. JSON scalar), that can be used for dynamic structures, like Maps.

Register it via:

RuntimeWiring.newRuntimeWiring().scalar(ExtendedScalars.Object)
0
Olga On

In code first approach (SPQR v0.9.6) adding @GraphQLScalar is enough. Or, as alternative, add scalar definition to GraphQLSchemaGenerator:

new GraphQLSchemaGenerator()
.withScalarMappingStrategy(new MyScalarStrategy())

And define MyScalarStrategy:

class MyScalarStrategy extends DefaultScalarStrategy {

@Override
public boolean supports(AnnotatedType type) {
  return super.supports(type) || GenericTypeReflector.isSuperType(MyScalarStrategy.class, type.getType());
}
}
0
Rasathurai Karan On

add dependency in your pom file

 <dependency>
  <groupId>com.graphql-java</groupId>
  <artifactId>graphql-java-extended-scalars</artifactId>
  <version>21.0</version>
</dependency>

then write a class to register scalar Component

@Configuration

public class ScalarRegister {

   @Bean
    public RuntimeWiring.Builder addLongScalar(RuntimeWiring.Builder builder) {
        return builder.scalar(ExtendedScalars.GraphQLLong);
    }

}

Then, you can use the Long Scalar, which means the Long type. Several scalar types are available, including GraphQLChar, GraphQLLong, GraphQLBigInteger, Currency, Url, Json, and LocalTime. from creating beans you can extend the scalars