How to pass JSON object in grpahql and strapi

2019-07-26 08:45发布

问题:

When I manually write the mutation query (in graphql plugin), it's working:

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

                      }
                    }
                  }

But if I code it and pass the exact same array I get an array of the exact same object I get [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

                      }
                    }
                  }`
            }

How can it be? Could it be a bug? I also tried with JSON.stringify but then got an error and the mutation didn't even come through

Thanks a lot in advance

回答1:

Constructing a query string this way is error-prone and dangerous; it opens you up to a slew of bugs and well-known security vulnerabilities. (What if newExamName is My "super-duper" exam!!!?)

GraphQL provides variables as a better approach to pass data in. In your case since you have a complex somewhat structured object, it's probably easiest to pass the whole input in as one object (other syntaxes are possible). I would expect this to look something like:

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]
      }
    }
  }
});

Now the HTTP client library can take responsibility for producing well-formed JSON from your input, and you're not performing tricky string manipulation.