Home > Mobile >  How to properly pass nested arrays as arguments for GraphQL API
How to properly pass nested arrays as arguments for GraphQL API

Time:10-25

I'm currently using AWS AppSync, however the question applies to general Graphql / Javascript / API.

I have the following nested data that I'm passing as an argument:

const DUMMY_DATA = [
['First Name', 'Last Name', 'company', 'email', 'phone', 'Address', 'City', 'State', 'Zip Code'],
['Lambert', 'Beckhouse', 'StackOverflow', '[email protected]', '512-555-1738', '316 Arapahoe Way', 'Austin', 'TX', '78721'],
['Maryanna', 'Vassman', 'CDBABY', '[email protected]', '479-204-8976', '1126 Troy Way', 'Fort Smith', 'AR', '72916']
]

I'm passing the above, as is, to my api, which looks something like this:

try {
  await doAPIWork({data: DUMMY_DATA})
} catch (err) {
  console.error(err)
}

However when it reaches my backend I'm unable to properly iterate through the nested arrays.

The nested array comes back as typeof String, and I'm unable to properly convert it back to an array... For instance DUMMY_DATA[0] comes back as ['First Name', 'Last Name', 'company' ....] with typeof string .

I know I'm either missing a step that I need to take before sending the data, or I'm failing to properly convert the string back to an array.

Would really appreciate any help on this!

Also: my current schema is

type Mutation {
  doAPIWork(data: [String]): String
    @function(name: "doAPIWork-dev")
}

and Ive also tried 

type Mutation {
  doAPIWork(data: [AWSJSON]): String
    @function(name: "doAPIWork-dev")
}

CodePudding user response:

You've got to parse the object before you can use it with JSON.parse(DUMMY_DATA)

This is not normally necessary when you use a graphql client and server (for example apollo-client and apollo-server) but that's not your configuration.

CodePudding user response:

Turns out the answer was pretty simple

change type to

type Mutation {
  doAPIWork(data: AWSJSON): String
    @function(name: "doAPIWork-dev")
}

and then pass the data as

try {
  await doAPIWork({data: JSON.stringify(DUMMY_DATA)})
} catch (err) {
  console.error(err)
}
  • Related