Search code examples
react-nativegraphqlaws-appsync

Create Connected object in GraphQL via Mutation


What is the best practice to create an object via mutation connected to another object.

Using the following schema:

type Question @model {
  id: ID!
  text: String!
  answers: [Answer] @connection(name: "QuestionAnswers")
}
type Answer @model {
  id: ID!
  text: String!
  question: Question @connection(name: "QuestionAnswers")
}

The following (and variants of it) fail:

mutation CreateAnswer {
  createAnswer(input: {
    text:"Yes",
    question: {
      id: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
    }
  }) 
    {
        id
    }
  }

Serverside code:

mutation CreateAnswer($input: CreateAnswerInput!) {
  createAnswer(input: $input) {
    id
    text
    question {
      id
      text
      answers {
        nextToken
      }
    }
  }
}

With the above, receiving the following error:

"Validation error of type WrongType: argument 'input' with value 'ObjectValue{objectFields=[ObjectField{name='text', value=StringValue{value='3'}}, ObjectField{name='question', value=ObjectValue{objectFields=[ObjectField{name='id', value=StringValue{value='9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8'}}]}}]}' contains a field not in 'CreateAnswerInput': 'question' @ 'createAnswer'"


Solution

  • Seems that this may be a naming convention in AppSync. The below worked for me:

    mutation createAnswer {
      createAnswer (input: {
        text: "5"
        answerQuestionId: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
      }) {
        id
      }
    

    Adding answer to QuestionId was what was needed.