首页 > 解决方案 > 在 graphql-yoga 中定义一个 Mutation 参数

问题描述

如何为定义为的解析器创建带有参数的突变graphql-yoga

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.jsgraphql

解决方案


根据您的类型定义:

  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在创建项目时为其设置 a,则需要将您的createProject定义修改为:

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

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

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

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

您需要这样做,因为您的createProject突变返回 a ProjectMutationResult,它本身包含一个projecttype 字段Project,它是定义idand字段的name字段。


推荐阅读