KrishnaFJ
KrishnaFJ

Reputation: 165

Custom Scalar in Graphql-java

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.

Upvotes: 11

Views: 17823

Answers (3)

Rasathurai Karan
Rasathurai Karan

Reputation: 801

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

Upvotes: 0

kaqqao
kaqqao

Reputation: 15469

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)

Upvotes: 9

Olga
Olga

Reputation: 3913

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());
}
}

Upvotes: 0

Related Questions