Lakshman Diwaakar
Lakshman Diwaakar

Reputation: 7579

sending an array to graphQL endpoint

The graphQL server is set up. It works properly when the values are hardcoded. Here is my invocation request:

"query": "mutation{
    createEvent(name: "+ name +", purpose: "+ purpose +", googleUserName: "+ googleUserName +", dateArray: "+ JSON.stringify(dateArray) +", attendees: [])
    {
      eventId
      name
      purpose
      googleUserName 
      dateArray 
      attendees{
         attendeeName
         personalizedDateSelection
         }
      }
   }"

This gives the error:

{"errors":
   [{"message":
     "Syntax Error GraphQL request (1:88) Expected :, found Name \"dateArray\"\n\n1: mutation{createEvent(name: lakshman, purpose: test, googleUserName: Diwaakartg Ganesh, dateArray: [\"Wed, Nov 9th 2016\",\"Thu, Nov 10th 2016\",\"Thu, Nov 3rd 2016\",\"Wed, Nov 2nd 2016\"], attendees: [])
      {eventId
       name
       purpose
       googleUserName
       dateArray
       attendees{
          attendeeName 
          personalizedDateSelection
          }
       }
    }\n}]}                                                                                      

There is no alignment error. I have made it so to enhance the readability But, the above mutation works properly when hardcoded the arguments. I find it pretty difficult to find what is the cause of the error. I have tried both JSON.stringify(dateArray) and just the dateArray alone.

Or is there a better approach to query GraphQL from react-redux app?

Upvotes: 1

Views: 1986

Answers (1)

stubailo
stubailo

Reputation: 6147

If you are trying to pass complex options, the best way to do that is to use variables. That way, you don't have to worry about formatting anything into the query string.

So you would send a request like this:

{
  "query": `
    mutation CreateEvent(
      $name: String!,
      $purpose: String!,
      $googleUserName: String!,
      $dateArray: [String],
      $attendees: [String]
    ) {
      createEvent(
        name: $name,
        purpose: $purpose,
        googleUserName: $googleUserName,
        dateArray: $dateArray,
        attendees: $attendees
      ) {
        eventId
        name
        purpose
        googleUserName 
        dateArray 
        attendees{
          attendeeName
          personalizedDateSelection
        }
      }
    }
  `,
  "variables": {
    "name": "...",
    "purpose": "...",
    "googleUserName": "...",
    "dateArray": [...],
    "attendees": []
  }
}

If you have worked with SQL before, it's the equivalent of using ? in your query and passing the arguments separately. Basically, you shouldn't be manually serializing and concatenating the query in your app, because variables are designed specifically for that case.

In fact, there are a lot of great reasons to keep your queries as completely static strings, as we outlined in this blog post.

Upvotes: 4

Related Questions