javascript - 在 Mutation 中使用 GraphQL Args 属性
问题描述
我正在使用 express 和 apollo-express 以及 mongodb (mongoose) 制作博客服务。
我做了一些突变查询,但我没有成功获得突变查询的参数。
现在我在问我应该如何构建我的变异查询以使事情正常工作。谢谢。
错误:
“消息”:“博客验证失败:标题:
title
需要路径。,slug:slug
需要路径。”
查询:
mutation ($input: BlogInput) {
newBlog(input: $input) {
title
slug
}
}
查询变量:
{
"input": {
"title": "ABC",
"slug": "abc"
}
}
我的 graphql 架构的一部分:
type Blog {
id: ID!
title: String!
slug: String!
description: String
users: [User]!
posts: [Post]!
}
input BlogInput {
title: String!
slug: String!
description: String
}
extend type Mutation {
newBlog(input: BlogInput): Blog
}
我的解析器的一部分:
import Blog from './blog.model'
export const blogs = async () => {
const data = await Blog.find().exec()
return data
}
export const newBlog = async (_, args) => {
const data = await Blog.create({ title: args.title, slug: args.slug })
return data
}
我的数据库架构的一部分(猫鼬):
import mongoose from 'mongoose'
const Schema = mongoose.Schema
const blogSchema = Schema({
title: {
type: String,
required: true
},
slug: {
type: String,
required: true,
unique: true
},
description: {
type: String
},
users: {
type: [Schema.Types.ObjectId],
ref: 'User'
},
posts: {
type: [Schema.Types.ObjectId],
ref: 'Post'
}
})
export default mongoose.model('Blog', blogSchema)
解决方案
你已经定义了你的newBlog
变异来接受一个名为input
. 据我所知,您正在使用变量正确地将该参数传递给突变。您的解析器接收传递给正在解析的字段的参数映射。这意味着您可以像这样访问对象的各个属性input
:
export const newBlog = async (_, args) => {
const data = await Blog.create({ title: args.input.title, slug: args.input.slug })
return data
}
请注意,您可能希望设置input
不可为空(即将类型设置为BlogInput!
),否则您的解析器将需要处理args.input
返回未定义的可能性。
推荐阅读
- c++ - 为什么 std::set::extract() 和 std::set::insert(nh) 的标准中没有不抛出保证?
- ansible - 合并多个任务以减少输出
- reactjs - 我在 CRA 和后端之间共享 Typescript 代码的方法:我错过了什么吗?
- c# - 将数据从一个 Gridview 中的行传输到另一个
- batch-file - 在回显语句批处理文件中使用增量变量而不一次又一次地修改它
- bash - 如何将“rename -n ...”输出到文件?
- powershell - 如何通过 Powershell 从在线 ZIP 存档中仅下载单个文件?
- openfaas - 如何通过openfass-cli在本地目录中使用我自己的openfaas模板?
- python - ValueError:传递的项目数错误 2,位置暗示 3
- git - Git:如何将外部文件夹(文件)添加到现有存储库中?