在表单数据中格式化带有片段的 GraphQL 突变

Format a GraphQL mutation with fragment in a Form Data

我想知道如何将包含片段的 GraphQL 突变正确格式化为表单数据中的有效 JSON。

背景

架构的类型 Comment 包含 Upload 标量。

import { GraphQLUpload } from 'graphql-upload';

const typeDefs = `
  scalar Upload

  type Comment {
    text: String
    files: [Upload!]
  }
`

const resolvers = {
  Upload: GraphQLUpload,
};

使用片段的客户端变异如下:

// 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)}
      \
    }`;
}

使用上面的突变将产生下面的表单数据结构。 这是根据 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--

上面的表单数据会产生错误

BadRequestError: Invalid JSON in the ‘operations’ multipart field (https://github.com/jaydenseric/graphql-multipart-request-spec).

如表单数据所示,由于多行字符串,"operations" 部分不是有效的 JSON。

所以我的问题是,如何正确地“打印”或格式化带有片段的突变,如下所示:

{
   "query":"mutation AddComment($text: String!, $files: [Upload!]) {  comment: addComment(text: $text, files: $files) {  ...Comment } } fragment Comment on Comment { text files }"
}

要解决此问题,请将 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]}}