【问题标题】:Is it possible to extend graphql response other than just data for pagination?除了分页数据之外,是否可以扩展 graphql 响应?
【发布时间】:2017-03-12 20:59:40
【问题描述】:

在 GraphQL 中响应通常如下所示。

{
  "data": [{
    "id": 1,
    "username": "Jon Snow",
    "email": "crow@northofthew.all",
    "age": 20
  }, {
    "id": 2,
    "username": "Tyrion Lannister",
    "email": "drunk@i.mp",
    "age": 34
  }, {
    "id": 3,
    "username": "Sansa Stark",
    "email": "redhead@why.me",
    "age": 17
  }]
}

是否可以将元数据添加到您的响应中,例如这样的分页。

{
  "pagination": {
    "total": 14,
    "count": 230,
  },
  "data": [{
    "id": 1,
    "username": "Jon Snow",
    "email": "crow@northofthew.all",
    "age": 20
  }, {
    "id": 2,
    "username": "Tyrion Lannister",
    "email": "drunk@i.mp",
    "age": 34
  }]
}

我正在使用 express-graphql,目前将这些分页放在自定义响应标头中,这很好,但可以更好。由于 GraphQL 响应已经被“数据”包裹,因此在其响应中添加更多“数据”并不是很奇怪。

【问题讨论】:

  • 根据规范,这不会是a valid GraphQL response(“为确保将来对协议的更改不会破坏现有的服务器和客户端,顶级响应映射不得包含除上述三个。”)。我猜你可以把它打包成一个extensions 键,或者use other pagination approaches
  • @CommonsWare 你是对的。谢谢!

标签: express response graphql


【解决方案1】:

根据规范,加强@CommonsWare 已经声明的内容,这将是无效的 GraphQL 响应。关于分页,Relay 有自己的分页方法,称为connections,但实际上,还有其他几种方法是可能的,甚至更适合某些情况(连接不是灵丹妙药)。

我想通过添加 GraphQL 的分层特性将相关数据置于同一级别来增强已经说过的内容。一个例子值千言万语,所以这里是:

query Q {
  pagination_info { # what is this info related to? completely unclear
    total
    count
  }
  user {
    friends {
      id
    }
  }
}

相反...

query Q {
  user {
    friends {
      pagination_info { # fairly obvious that this is related to friends
        total
        count
      }
      friend {
        id
      }
    }
  }
}

【讨论】:

  • 这完全有道理。我明白这意味着什么。谢谢。
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 2021-03-23
  • 2012-05-10
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多