【问题标题】:Defining a Mutation argument in graphql-yoga在 graphql-yoga 中定义一个 Mutation 参数
【发布时间】:2019-02-10 21:22:02
【问题描述】:

如何为 graphql-yoga 中定义的解析器创建带有参数的 Mutation:

const resolvers =
  Mutation: {
    createProject(root, args) {
      const id = (Number(last(data.projects).id) + 1).toString()
      const newProject = { ...args, id: id }
      ...

我尝试了以下方法:

mutation CreateProject($name: String!) {
  createProject {
    data: {
      name: $name
    }
  }
}

mutation CreateProject($name: String!) {
  createProject($name: name) {
    statusCode
  }
}

产生

以及其他各种结构均未成功。

在项目 README 或三个示例中的任何一个中似乎都没有提到 Mutation。

更新

我现在正在使用:

mutation CreateProject($name: String!) {
  createProject(name: $name) {
    id
    name
  }
}

这与我在网上看到的示例非常相似,我认为它必须是有效的并且语法没有被拒绝。

架构定义为:

  scalar ID

  type Project {
    id: ID
    type: ProjectType
    name: String
  }

  interface MutationResult {
    statusCode: Int
    message: String
  }

  type ProjectMutationResult implements MutationResult {
    statusCode: Int
    message: String
    project: Project
  }

  type Mutation {
    createProject: ProjectMutationResult
  }

但是在提交突变时,我收到:

{
  "error": {
    "errors": [
      {
        "message": "Unknown argument \"name\" on field \"createProject\" of type \"Mutation\".",
        "locations": [
          {
            "line": 2,
            "column": 17
          }
        ]
      },
      {
        "message": "Cannot query field \"id\" on type \"ProjectMutationResult\".",
        "locations": [
          {
            "line": 3,
            "column": 5
          }
        ]
      },
      {
        "message": "Cannot query field \"name\" on type \"ProjectMutationResult\".",
        "locations": [
          {
            "line": 4,
            "column": 5
          }
        ]
      }
    ]
  }
}

【问题讨论】:

  • 如果您看到错误,请将其包含在您的问题中。这不仅有助于解决您的问题,还可以帮助其他人在搜索时找到您的问题。
  • 由于语法错误,图形页面不允许我提交查询。我会看看我是否可以捕获它产生的工具提示。

标签: node.js graphql


【解决方案1】:

根据你的类型定义:

  1. createProject 突变不需要任何参数:
type Mutation {
  createProject: ProjectMutationResult
}
  1. ProjectMutationResult 类型没有id 字段,也没有name 字段:
type ProjectMutationResult implements MutationResult {
  statusCode: Int
  message: String
  project: Project
}

所以当你运行突变时:

mutation CreateProject($name: String!) {
  createProject(name: $name) {
    id
    name
  }
}

您为 GraphQL 服务器提供的内容与它实际期望的内容之间存在完全差异。

首先,如果您希望能够在创建项目时为其设置name,则需要将您的createProject 定义修改为:

type Mutation {
  createProject(name: String!): ProjectMutationResult
}

(如果您希望命名是可选的,请将名称设置为String 类型而不是String!

然后,假设您要从突变中检索新创建的项目 id 和名称,请将突变本身更改为:

mutation CreateProject($name: String!) {
  createProject(name: $name) {
    project {
      id
      name
    }
  }
}

您需要这样做,因为您的createProject 突变返回一个ProjectMutationResult,它本身包含一个Project 类型的project 字段,它是定义idname 字段的字段。

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 2022-06-11
    • 2020-12-23
    • 2021-03-30
    • 2020-05-22
    • 2018-12-08
    • 2019-04-02
    • 2020-10-12
    • 2019-01-13
    相关资源
    最近更新 更多