node.js - 在 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
}
]
}
]
}
}
解决方案
根据您的类型定义:
createProject
突变不期望任何论点:
type Mutation {
createProject: ProjectMutationResult
}
- 该
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
,它本身包含一个project
type 字段Project
,它是定义id
and字段的name
字段。
推荐阅读
- openshift - OpenShift3 在线 CPU 资源限制
- postgresql - 可以创建外键以指向 PostgreSQL 中日期范围版本表中的非唯一列吗?
- powershell - enter-pssession 的问题:“找不到接受参数的位置参数”
- sql - 获取每月 25 日后的第 6 个工作日加上 5 个工作日的语法错误
- dart - 在 Dart 中,将动态转换为给定类型或返回 null 的语法好方法?
- javascript - 如何在动态内部级别中仅获取 mongodb 中的一个字段?
- vue.js - 如何在 VueJS 中枚举特定组件类型的子虚拟机?
- amazon-web-services - AWS 事件溯源实施
- node.js - 过滤器电子隐藏的项目
- python - 如何使用 Selenium Python XPATH 获取文本