简体   繁体   中英

Submit graphql mutation containing nested array of object playload with "aws-amplify"

I trying to submit below payload (nested array of objects) using aws-amplify :

{
  "data": [
    { "name": "alpha", "description": "lorem" },
    { "name": "bravo", "description": "ipsum" },
  ]
}

This solution (source code is TypeScript):

import AWSAmplifyAPI, { graphqlOperation } from "@aws-amplify/api";


const rawGraphQLRequest: string = `
  mutation ($data: [registerMultipleItemsInput]!) {
    registerMultipleItems(data: [$data])
  }`;

type Item = {
  name: string;
  description: string;
}

async function registerMultipleItems(items: Array<Item>): Promise<void> {
  await AWSAmplifyAPI.graphql(graphqlOperation(rawGraphQLRequest, { data: items }));
}

causes unclear error:

Validation error of type VariableTypeMismatch: Variable type '[registerMultipleItemsInput]!' doesn't match expected 
type 'registerMultipleItemsInput' @ 'registerMultipleItems'";

Is backend, the scheme defined as:

registerMultipleItems(data: [registerMultipleItemsInput]!): [String]!
    @aws_cognito_user_pools

input registerMultipleItemsInput{
  name: String!
  description: String!
}

I tried to add registerMultipleItemsInput definition to rawGraphQLRequest :

const rawGraphQLRequest: string = `

  input registerMultipleItemsInput {
    name: String!
    description: String!
  }

  mutation ($data: [registerMultipleItemsInput]!) {
    registerMultipleItems(data: [$data])
  }`;

Above error left, and additional error occurred:

Validation error of type NonExecutableDefinition: The registerMultipleItemsInput definition is not executable.

What the correct syntax for { "data": <Array> } payload?

PS I hope I don't need to define registerMultipleItemsInput in rawGraphQLRequest , because registerMultipleItemsInput already has been defined in backend and defining it again in frontend is some kind of hardcoding.

I think your first solution is correct except for:

mutation ($data: [registerMultipleItemsInput]!) {
    registerMultipleItems(data: [$data]) // <-------- incorrect
}`;

$data already contains an array of registerMultipleItemsInput but you've wrapped it in another array which is incorrect, it must be:

mutation ($data: [registerMultipleItemsInput]!) {
    registerMultipleItems(data: $data) // <-------- correct
}`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM