我是GraphQL的新手,我试图做一个突变来从我的数据库中删除一篇文章,但我无法弄清楚如何。我使用Node.js,Mongoose和GraphQL。
这是我架构上的突变。
const Mutation = new GraphQLObjectType({
name: 'Mutation',
description: 'Articles Mutations',
fields: () => ({
remove: {
type: articleType,
description: 'Deletes an article by id',
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (value, {id}) => {
return db.Article.findOneAndRemove({_id: new ObjectId(id)});
}
}
})
});
这是我在调用API删除文章时使用的查询。
export const DELETE_ARTICLE_QUERY = (id) => (`{
remove(id: "${id}") {
id
author
content
published
tags
title
excerpt
}
}`);
我做错了什么?
我收到400 Bad Request错误。消息:"无法查询字段"删除" on type" Mutation"。"
答案 0 :(得分:2)
在发出GraphQL请求时,最好始终指定您正在执行的操作类型(查询或突变)。如果您没有这样做,GraphQL会假设您正在进行查询,这不是这里的情况。你没有说明你是否看到任何错误,但是我猜赌GraphQL会返回类似cannot query field remove on Query
的内容。
修改DELETE_ARTICLE_QUERY以包含操作:
export const DELETE_ARTICLE_QUERY = (id) => (`mutation {
将调试目的包含在操作名称中是一种很好的做法,因此您也可以这样说:
export const DELETE_ARTICLE_QUERY = (id) => (`mutation DeleteArticle {
编辑:根据您提供的错误,听起来架构对象未正确设置。看起来应该是这样的:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "WhateverNameYouWantForQuery",
fields: {
// each query is a property here
}
}),
mutation: new GraphQLObjectType({
name: "WhateverNameYouWantForMutation",
fields: {
// each mutation is a property here
}
}),
});
如果将突变定义为单独的变量(Mutation
),则可以将突变属性的值作为该变量来协助:
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
// query props
}),
mutation: Mutation
}),
});
这是一个工作示例,您可以开箱即用并玩弄。启动服务器后,您可以在浏览器中访问http://localhost:3000/graphql
以访问GraphiQL界面,并在那里使用潜在的查询/突变。
const graphqlHTTP = require('express-graphql');
const app = require('express')();
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLNonNull,
GraphQLString,
GraphQLList
} = require('graphql');
const articleType = new GraphQLObjectType({
name: 'Article',
fields: {
title: {
type: GraphQLString,
},
},
});
const Mutation = new GraphQLObjectType({
name: "RootMutationnnnn",
fields: () => ({
remove: {
type: articleType,
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (value, {id}) => {
return {title: 'Testing a delete'};
}
}
})
});
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: "RootQueryyyyy",
fields: {
articles: {
type: new GraphQLList(articleType),
resolve: () => {
return [{title: 'Test title'}, {title: 'Test title'}];
}
}
}
}),
mutation: Mutation
});
const root = {};
app.post('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: false,
}));
app.get('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));
app.listen(3000, function(){
console.log('listening on port 3000');
});