【问题标题】:Can I resolve fields that are not in the model with @GraphQLQuery我可以使用@GraphQLQuery 解析模型中没有的字段吗
【发布时间】:2021-03-03 18:27:30
【问题描述】:

我们正在使用 graphql-spqr 从我们的 Java 后端 api 和模型生成 graphql 架构。

今天以获取产品为例,我们注释了一个看起来像这样的方法:

@GraphQLQuery
List<Product> allProducts() {...}

我们希望避免创建新端点来检索 Product 中的额外字段。

有没有办法为不属于模型的字段定义解析器?(注解与否)

作为一个例子,假设我们的 java 模型是一个 Product + 两个端点:

class Product {
   String id;
   String name;
}

class Frame {
  String id;
}

// and some kind of relationship between the two
class ProductToFrame {
  String productId;
  String frameId
}

List<Product> allProducts();
List<Frame> getFramesByProductId(String productId);

我们希望我们的 graphql 模式看起来像这样:

type Product {
  id: String
  name: String

  frames: [Frame] 
}

type Frame {
  id: String
}

【问题讨论】:

    标签: java graphql-java graphql-spqr


    【解决方案1】:

    您只需要这样的东西(例如,在您现有的 allProducts() 方法旁边:

    @GraphQLQuery
    public List<Frame> frames(@GraphQLContext Product product) {
        return getFramesByProductId(product.getId());
    }
    

    frames 字段随后将附加到它的 contextual Product 类型。或者换句话说:Product 类型将根据需要获得一个名为 frames 的额外字段。

    确保您查看了 SPQR 中的测试。它们充当大多数功能的展示。

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 2011-01-27
      • 2011-04-11
      相关资源
      最近更新 更多