Custom Scalar in Graphql-java

和自甴很熟 提交于 2019-11-28 05:29:19

问题


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.


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/46034801/custom-scalar-in-graphql-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!