Reputation: 21
The following request works when I post the mutation from GraphiQL but does not work from the client-side of my app.
I get a "POST http://localhost:3001/graphql 400 (Bad Request)" error in the console.
const post = {
userId: store.user.id,
imageURLs: store.post.request.aws.imageURLs,
tags: store.post.tags,
link: store.post.link,
};
const query = `mutation CreatePost($post: PostInput) {
createPost(post: $post) {
user,
tags,
imageURLs,
link
}
}`;
return fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables: {
post,
},
}),
credentials: 'include',
})
Does anyone know what is going on?
Upvotes: 2
Views: 1125
Reputation: 5529
A lot of what you have seems to be just fine, except that you have mutation function on the input payload and type:
mutation CreatePost($post: PostInput) { ... // CreatePost is not needed
Here is a quick working example to better explain what you need for mutations using an InputObject, and using fetch/node-fetch for the request:
fetching.js
let postUpdate = {
id: randomInt,
name: newPost.name
};
let url = 'http://localhost:4001/graphql';
let query = `mutation ($postUpdate: PostInput) {
updatePost(postArgs: $postUpdate) { id, name }
}`;
let mutateInit = {
mode: 'cors',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
variables: {
postUpdate
},
})
};
fetch(url, mutateInit)
.then(res => res.text())
.then(out => {
console.log('Mutate response:', out);
});
Schema.js
...
const PostInput = new GraphQLInputObjectType({
name: 'PostInput',
description: 'Mutation Input',
fields: () => ({
num: {type: new GraphQLNonNull(GraphQLInt)},
name: {type: new GraphQLNonNull(GraphQLString)}
})
});
const Mutation = new GraphQLObjectType({
name: 'PostMutations',
description: 'Mutations for the Posts',
fields: () => ({
updatePost: {
type: Post,
args: {
postArgs: { type: PostInput }
},
resolve: (value, { postArgs }) => {
let post = Object.assign({}, postArgs);
return post;
}
}
})
});
...
Based on the other examples out there, it seems there is an issue with some ambiguous variables that could cause confusion for many. With this example we can now see the different variables that are required in the actual query. To make even more sense out of it, let's look at what this query is referencing:
mutation ($<mutation_payload>: <Input Type>) {
<mutation_function>(<function_argument_name>: $<mutation_payload>) { <returned fields> }
}
As long as these are all resolving to the above sections correctly, the fetch query should go through without a hitch. If they do not you will find yourself with all sorts of issues ranging from "cannot return null for non-nullable" when the payload isn't going where it should, to errors complaining about the GraphQL query itself because something is missing like an input type.
Upvotes: 1