How can I send a GraphQL AJAX query with a variabl

2020-07-22 09:19发布

问题:

I am trying to make an API call to GitHub using GraphQL, I have been able to successfully call data with a static graphQL call, however I am having trouble putting a variable (var entry) in my call so that I can change the call based on an input a user would provide in the web app.

I am using AJAX to be able to pass the authorization token. Additionally, the call does not work unless the query is JSON stringified (gets 400 error otherwise).

The JSON Stringify seems to turn the name of the variable 'superQuery' into a string rather than turning the value of 'superQuery' into a string.

How can I send a graphQL query with a variable that can change based on user input?

P.S. Relative noob to web development, apologies for any super obvious mistakes.

Here is what I have so far:

var entry = $('#entry').val()

  var superQuery = `{
    repository(name: entry, owner: "******") {
      pullRequests(last: 100) {
        nodes {
          state
          headRepository {
            owner {
             login
            }
           }
          }
         }
        }
       }`

.ajax({
  method: "POST",
  url: "https://api.github.com/graphql",
  contentType: "application/json",
  headers: {
    Authorization: "bearer **********************************"
  },
  data: JSON.stringify({
    query: superQuery
  })
})

回答1:

For anyone with the same problem, here is what the code looked like when I finally got it to work:

      $('button').click(function() {
      event.preventDefault();
      var entry = $('#entry').val()
      console.log(entry);


      $.ajax({
          method: "POST",
          url: "https://api.github.com/graphql",
          contentType: "application/json",
          headers: {
            Authorization: "bearer ***********"
          },
          data: JSON.stringify({
            query: `query ($entry: String!) {repository(name: $entry, 
            owner: "*******") { pullRequests(last: 100) {
              nodes {
                state
                headRepository {
                  owner {
                    login
                  }
                }
              }
            }
          }
        }`,
        variables: {
          "entry": $('#entry').val()
        }
      })
    })


回答2:

If I understand your question correctly, I believe you want to do the following (assuming entry is a string):

 var superQuery = `query repository($entry: String)
         repository(entry: $entry) {
            pullRequests(last: 100) {
               nodes {
                 state
                 headRepository {
                   owner {
                     login
                    } 
                  } 
                } 
             }
          }`

And then for your data:

data: JSON.stringify({
   query: superQuery,
   variables: { entry: entry }
})