Graphql-java中的自定义标量

我们计划在我们的应用程序中使用Graphql作为后端服务器。 我们选择Graphql-Java来开发我们的POC。 我们遇到了一个创建我们自己的scalartype来处理java.util.Map对象类型的方法。

我们还没有找到有关创建自定义标量类型的任何文档。 在示例代码中如下

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

如何为CustomScalar对象完成实现。 需要帮忙。

要了解如何制作标量,只需查看现有标量并执行类似操作即可。

对于动态对象标量,请查看graphql-spqr的对象标量实现并执行类似的操作:

 public static GraphQLScalarType graphQLObjectScalar(String name) { return new GraphQLScalarType(name, "Built-in object scalar", new Coercing() { @Override public Object serialize(Object input) { return input; } @Override public Object parseValue(Object input) { return input; } @Override public Object parseLiteral(Object input) { return parseFieldValue((Value) input); } //recursively parse the input into a Map private Object parseFieldValue(Value value) { if (value instanceof StringValue) { return ((StringValue) value).getValue(); } if (value instanceof IntValue) { return ((IntValue) value).getValue(); } if (value instanceof FloatValue) { return ((FloatValue) value).getValue(); } if (value instanceof BooleanValue) { return ((BooleanValue) value).isValue(); } if (value instanceof EnumValue) { return ((EnumValue) value).getName(); } if (value instanceof NullValue) { return null; } if (value instanceof ArrayValue) { return ((ArrayValue) value).getValues().stream() .map(this::parseFieldValue) .collect(Collectors.toList()); } if (value instanceof ObjectValue) { return ((ObjectValue) value).getObjectFields().stream() .collect(Collectors.toMap(ObjectField::getName, field -> parseFieldValue(field.getValue()))); } //Should never happen, as it would mean the variable was not replaced by the parser throw new IllegalArgumentException("Unsupported scalar value type: " + value.getClass().getName()); } }); } 

在代码优先方法(SPQR v0.9.6)中添加@GraphQLScalar就足够了。 或者,作为替代方案,将标量定义添加到GraphQLSchemaGenerator:

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

并定义MyScalarStrategy:

 class MyScalarStrategy extends DefaultScalarStrategy { @Override public boolean supports(AnnotatedType type) { return super.supports(type) || GenericTypeReflector.isSuperType(MyScalarStrategy.class, type.getType()); } }