如何在 grpahql 和 Strapi 中传递 JSON 对象

sir*_*ver 2 json graphql strapi

当我手动编写突变查询(在 graphql 插件中)时,它正在工作:

mutation {
                    createExam(input: {
                      data: {
                        name: "myName"
                        desription: "ggg"
                        questions: [{gf: "hello"}]
                        time: 2
                        subjects: ["5c468e2d61670b25b46ccdfe"]
                      }
                    }) {
                      exam {
                        name
                                desription
                        time

                      }
                    }
                  }
Run Code Online (Sandbox Code Playgroud)

但是如果我编码它并传递完全相同的数组,我会得到一个完全相同对象的数组,我得到 [null, null]

let parsedQuestion = [{gf: "hello"}];

 const response = await strapi.request('POST', '/graphql', {
            data: {
                query: `mutation {
                    createExam(input: {
                      data: {
                        name: "` + examInfo.newExamName + `"
                        desription: "` + examInfo.newExamDescription + `"
                        time: ` + Number(examInfo.newExamTime) + `,
                        questions: `+ parsedQuestion + `, 
                        subjects: ["` + this.state.modalSubject._id + `"]
                      }
                    }) {
                      exam {
                        name
                        desription
                        time
                        questions

                      }
                    }
                  }`
            }
Run Code Online (Sandbox Code Playgroud)

怎么会这样?这可能是一个错误吗?我也尝试过 JSON.stringify 但后来出现错误并且突变甚至没有通过

非常感谢提前

Dav*_*aze 5

以这种方式构造查询字符串容易出错且危险;它使您面临大量错误和众所周知的安全漏洞。(如果newExamNameMy "super-duper" exam!!!呢?)

GraphQL 提供变量作为传递数据的更好方法。在您的情况下,由于您有一个复杂的结构化对象,将整个输入作为一个对象传递可能是最简单的(其他语法也是可能的)。我希望这看起来像:

const response = await strap.request('POST', '/graphql', {
  data: {
    query: `mutation CreateExam($input: CreateExamInput!) {
      createExam(input: $input) {
        exam { name, desription, time, questions }
      }
    }`,
    variables: {
      input: {
        name: examInfo.newExamName,
        desription: examInfo.newExamDescription,
        time: Number(examInfo.newExamTime),
        questions: [{gf: "hello"}],
        subjects: [this.state.modalSubject._id]
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

现在 HTTP 客户端库可以负责从您的输入生成格式良好的 JSON,并且您无需执行棘手的字符串操作。