如何在 GraphQL SPQR 中像 parent 一样对待 child class

How to treat a child class like its parent in GraphQL SPQR

我围绕 BigDecimal 创建了一个包装器。基本上只是在它上面放了一堆更友好的方法。我将它用于我的一些 POJO 字段,它会生成这样的模式

# Built-in java.math.BigDecimal
scalar BigDecimal

input BestDecimalInput {
  scale: Int!
}

理想情况下,当我进行查询时,我能够像对待 BigDecimal 一样对待它。我有一个构造函数

public BestDecimal(double val) {
        super(val);
    }

我希望它能让我在我的 query/mutation 中使用常规浮点数,但它似乎不能那样工作。基本上,如果下面是 BestDecimal object,我希望它能像 BigDecimal 一样工作。

myquery(number: 10){
  whatever
}

您可以做 2 件事。

  • 将您 class 映射为自定义标量。为此,您必须实现自定义 TypeMapper 并将其连接起来。

  • 或者,您可以提供自定义 TypeAdapter,将 BestDecimal 调整为 BigDecimal,反之亦然。

查看 TypeMapperTypeAdapter 的现有实现,例如OptionalIntAdapter (that makes OptionalInt act as an Integer), and make a new one based on that. Or see 用于自定义标量。

您可以使用 generator.withTypeMappersgenerator.withTypeAdapters 连接它。

使用 Spring Starter,您可以像这样添加 TypeMapper

@Bean
public ExtensionProvider<GeneratorConfiguration, TypeMapper> mappers() {
    //After IdAdapter is generally a safe place to insert custom mappers
    return (config, mappers) -> mappers.insertAfter(IdAdapter.class, new YouCustomMapper());
}

不幸的是,您不能直接连接 TypeAdapter。您必须同时将其连接为 TypeMapperInputConverterOutputConverter,这很烦人。因此,添加一个自定义模块会更容易,该模块添加了 TypeAdapter:

@Bean
public ExtensionProvider<GeneratorConfiguration, Module> modules() {
    return (config, modules) -> modules.append(context -> 
         context.getSchemaGenerator().withTypeAdapters(new YourCustomAdapter()));
}

你当然可以(也应该)做一个合适的 Module class 而不是像我那样匿名。