[英]Format a GraphQL mutation with fragment in a Form Data
I would like to know how to properly format a GraphQL mutation containing a fragment as a valid JSON in a form data.我想知道如何正确格式化包含一个片段的 GraphQL 突变作为表单数据中的有效 JSON。
The schema has a type Comment
containing an Upload
scalar.该模式有一个类型Comment
,其中包含一个Upload
标量。
import { GraphQLUpload } from 'graphql-upload';
const typeDefs = `
scalar Upload
type Comment {
text: String
files: [Upload!]
}
`
const resolvers = {
Upload: GraphQLUpload,
};
The client mutation using a fragment is as follows:使用片段的客户端突变如下:
// mutation.js
export const Comment = gql`
fragment Comment on Comment {
text
files
}
`;
export const addComment = gql`
mutation AddComment($text: String!, $files: [Upload!]) {
comment: addComment(text: $text, files: $files) {
...Comment
}
${Comment}
}
`
// saga.js
import { print } from "graphql";
function addComment() {
// ...
const operation = `{ \
"query": "${print(Mutation.addComment)}", \
"variables": \
${JSON.stringify(variables)}
\
}`;
}
Using the mutation above will yield the form data structure below.使用上面的突变将产生下面的表单数据结构。 This is structured according to the graphql-multipart-spec
.这是根据graphql-multipart-spec
构造的。
------WebKitFormBoundaryxwxfmamlvsNq5eL1
Content-Disposition: form-data; name="operations"
{ "query": "mutation AddComment($text: String!, $files: [Upload!]) { comment: addComment(text: $text, files: $files) {
...Comment
}
}
fragment Comment on Comment {
text
files
}
", "variables": {"text":"Lorem Ipsum","files":[]}
}
------WebKitFormBoundaryxwxfmamlvsNq5eL1
Content-Disposition: form-data; name="map"
{}
------WebKitFormBoundaryxwxfmamlvsNq5eL1--
The form data above will generate an error上面的表单数据会产生错误
BadRequestError: Invalid JSON in the ‘operations’ multipart field (https://github.com/jaydenseric/graphql-multipart-request-spec).
As seen in the form data, the "operations"
part is not a valid JSON due to the multi-line string.从表单数据中可以看出,由于多行字符串, "operations"
部分不是有效的 JSON。
So my question is, how to properly "print" or format a mutation with a fragment as shown below:所以我的问题是,如何正确“打印”或使用片段格式化突变,如下所示:
{
"query":"mutation AddComment($text: String!, $files: [Upload!]) { comment: addComment(text: $text, files: $files) { ...Comment } } fragment Comment on Comment { text files }"
}
To solve this is to move JSON.stringify()
in the proper location.解决这个问题的方法是将JSON.stringify()
移动到正确的位置。
// stringify entire operation instead of variables (only)
const operation = JSON.stringify({
query: print(Mutation.addComment),
variables: variables
});
{"query":"mutation AddComment($text: String!, $files: [Upload!]) {\n comment: addComment(text: $text, files: $files) {\n ...Comment\n }\n}\n\nfragment Comment on Comment {\n text\n files\n}\n","variables":{"text":"Lorem Ipsum","files":[null]}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.