graphql - GraphQL - 未由操作定义的变量
问题描述
我的 GraphQL 架构定义为:
type Query {
getEntity(id: Int!): Entity
getEntityUsers(entityId: Int!, statusId: Int): [User]
}
type Entity {
id: Int!
name: String!
email: String!
logo: String
createdAt: DateTime!
updatedAt: DateTime!
users(statusId: Int): [User]
}
如您所见,我有两种方法可以获取Entity
对象的用户。当前适用于我的查询的是getEntityUsers
根解析器方法。此查询如下所示:
query getEntityUsers($entityId: Int!, $statusId: Int) {
users: getEntityUsers(entityId: $entityId, statusId: $statusId) {
...
}
}
..带有变量:
{
entityId: 1,
statusId: 2
}
有没有办法让我通过其他方式statusId
?现在查询看起来像这样:
query getEntity($id: Int!) {
entity: getEntity(id: $id) {
...
users (statusId: 2) {
...
}
}
}
这显然适用于变量:
{
id: 1
}
但是,如果我想使用第二种方法并更改statusId
? statusId
如果它没有在根解析器上定义,是否有传递?
我试过查询:
query getEntity($id: Int!) {
entity: getEntity(id: $id) {
...
users (statusId: $statusId) {
...
}
}
}
..带有变量:
{
id: 1,
statusId: 2
}
但我只是得到错误:Variable "$statusId" is not defined by operation "getEntity".
有没有办法做到这一点?
解决方案
每个操作(查询或突变)都必须明确定义您在该操作中使用的任何变量。因此,如果您有一个名为 的变量$statusId
,则必须将该变量的类型指定为操作定义的一部分:
query getEntity($id: Int!, $statusId: Int) {
# your selection set here
}
在查询中使用这些变量的位置(无论是在根级别还是其他地方)是无关紧要的——它们必须始终定义为操作定义的一部分。
推荐阅读
- mapbox - Mapbox Direction GL - 显示/隐藏驾驶说明
- ios - 使用AllowedCharacters 快速编码url 不能将%20 编码为%2520(意味着将% 编码为%25)
- javascript - 按下键时如何触发事件
- javascript - index.js 转换为 index.ts 但看到我无法理解的奇怪错误
- django - Django 表单和 CBV CreateView 无法将 request.user 分配给用户字段
- python - mypy "Optional[Dict[Any, Any]]" 在标准过滤器、地图中不可索引
- html - 悬停时侧边栏不出来
- reactjs - 当某些条件通过时,如何在反应中启用和禁用 p 标签
- awk - AWK 命令将 YYYYMMDD 减少 4 年
- python-3.x - Cloud Run 连接到 Cloud SQL 模块错误 Python