【问题标题】:GraphQL pass @include logic to the repository callGraphQL 将 @include 逻辑传递给存储库调用
【发布时间】:2018-08-18 02:54:57
【问题描述】:

我有一个问题

{
    "query": "query($withComments: Boolean!) {feed(id: 2) {name comments @include(if: $withComments) {title text}}}",
    "vars": {"withComments": true}
}

基于withComments 变量,我可以抓取带有或不带有cmets 的提要。有用。但似乎 Sangria 在任何情况下都必须使用 cmets 获取提要(对我来说性能问题是什么),即使我不需要它们并通过 withCommentsfalse 值:

val QueryType = ObjectType(
    "Query",
    fields[GraphQLContext, Unit](
      Field("feed", OptionType(FeedType),
        arguments = Argument("id", IntType) :: Nil,
        resolve = c => c.ctx.feedRepository.get(c.arg[Int]("id")))))

如果我没有@include,那么在对象中包含/排除继承列表(比如关系)并且不从存储库中选择所有数据的正确方法是什么,让存储库知道它?

如果解决方案是进行两个查询 feedfeedWithComments 我看不到 @include 的任何灵活性。

【问题讨论】:

    标签: scala graphql sangria


    【解决方案1】:

    由于您的数据访问对象(资源库)和 GraphQL 架构彼此分离,因此您需要明确传播有关特定字段的包含/排除的信息。

    有很多方法可以解决这个问题,但我认为最简单的一种是使用projections。在您的情况下,它可能如下所示:

    val IdArg = Argument("id", IntType)
    
    val QueryType = ObjectType(
      "Query",
      fields[GraphQLContext, Unit](
        Field("feed", OptionType(FeedType),
          arguments = IdArg :: Nil,
          resolve = Projector(1, (c, projection) ⇒
            if (projection.exists(_.name == "comments"))
              c.ctx.feedRepository.getWithComments(c arg IdArg)
            else
              c.ctx.feedRepository.getWithoutComments(c arg IdArg)))))
    

    对于Projector,我要求图书馆为我提供嵌套字段的 1 级深度投影(只是字段名称)。然后根据这些信息,我可以以不同的方式(使用或不使用 cmets)获取数据

    【讨论】:

    • 谢谢,它是有效的,这正是我想要的,也是他们在文档中推荐的(可惜没有例子)。 @include 让我失望了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2019-02-18
    相关资源
    最近更新 更多