Edgaras Karka
Edgaras Karka

Reputation: 7852

How to pass array of objects to the graphql query from js client

I want pass to server array of object throw graphql API.

my query on the schema:

export const schema = buildSchema(`
  type Query {
    statistics(
      modelId: String
      picksEnds: [PickEnd]        
    )
  }: Statistics
  type PickEnd {
    end: String
    limit: float
  } 
  ...
`)

my js based query on clients side:

 const createStatisticsQuery = (...) => {
     return `query {
             statistics(
               modelId: "${modelId}", 
               picksEnds: ${JSON.stringify(myEnds)}
             ) ...

but get error from graphql:

message: "Syntax Error: Expected Name, found String "end""

snippet from request payload:

{"query":"query {\n statistics(\n modelId: \"5ca0f4afb88b3a2e006faa0d\",\n picksEnds: [{\"end\":\"home\"},{\"end\":\"draw\"},{\"end\":\"away\"},{\"end\":\"under\",\"limit\":0.5},{\"end\":\"over\",\"limit\":0.5},{\"end\":\"under\",\"limit\":1.5 ...

Upvotes: 2

Views: 8229

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84657

While GraphQL syntax is similar to JSON, you cannot use JSON inside a GraphQL document, which is what you're doing by calling JSON.stringify and then inserting the result into your template string.

What GraphQL expects:

[{end:"foo",limit:2.0}]

What using stringify does:

[{"end":"foo","limit":2.0}]

Since this syntax is not valid, an error is thrown. The easiest way to get around this issue is to utilize variables to provide the needed input, since variable values are provided as JSON.

# Note: Replace PickEndInput with whatever your input type is actually called
query StatsQuery($id: String!, $ends: [PickEndInput!]!) {
  statistics(modelId: $id, picksEnds: $ends) {
    # ...
  }
}

You can then construct a JavaScript object for the variables and pass it along to fetch, axios or whatever you're using to make your request. For example:

const variables = {
  id: 'SOME_ID',
  ends: [
   {
     end:'foo',
     limit: 2.0,
   },
  ],
}
const query = ...
fetch('SOME_ENDPOINT_URL', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ variables, query }),
})

Ideally, you'd want to use an existing client like Apollo to make these calls easier.

Upvotes: 7

Related Questions