【问题标题】:GraphQL - do not return empty objects of an interfaceGraphQL - 不返回接口的空对象
【发布时间】:2018-06-18 13:49:31
【问题描述】:

给定

interface Interface {
  common: String!
}

type A implements Interface {
  common: String!
  foo: String!
}

type B implements Interface {
  common: String!
  bar: String!
}

是否可以构造一个查询,默认返回[Interface]只返回As,并过滤掉Bs/空对象?

当结果集中有AB

query {
  q {
    ... on A {
      foo 
    }
  }
}

返回一个A 和一个空对象(因为我们在其他情况下不要求提供数据):

{
  "data": {
    "q": [
      {
        "foo": "foo"
      },
      {}
    ]
  }
}

有关完整示例,请参阅 https://launchpad.graphql.com/zrz504kp37

【问题讨论】:

  • 你可以做到。但是确定 A 或 B 的区别因素是什么?或者您可以在解析器函数中检查空对象并删除这些条目并返回剩余的

标签: graphql apollo graphql-js


【解决方案1】:

我遇到了同样的问题,但在我的情况下,我使用了 GraphQL (PHP) 和一个名为 overblog/GraphQLBundle 的 symfony 包,它提供了一些回调(事件),在我的情况下,我使用了帖子执行一个:

public function onPostExecutor(ExecutorResultEvent $event)
{
    $result = $event->getResult();

    // Here I loop over the data array and unset all these empty {} objects.
}

这是供参考的文档: https://github.com/overblog/GraphQLBundle/blob/master/Resources/doc/events/index.md

我猜你可以为 JS 使用类似的东西。

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 2020-01-25
    • 2020-05-09
    • 2020-04-03
    • 2021-12-18
    • 2011-08-17
    • 2020-04-08
    • 2018-08-22
    • 2019-08-06
    相关资源
    最近更新 更多