graphqlmutationgraphql-mutation

How to mutate a list of objects in an array as an argument in GraphQL completely


I cannot mutate a list of objects completely, because only the last element of the array will be mutated.

What already works perfectly is, if I put each element ({play_positions_id: ...}) in the array manually like here:

mutation CreateProfile {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: [{play_positions_id: {id: "1"}}, {play_positions_id: {id: "2"}}]}) {
    id
    status
    play_positions {
     
      play_positions_id {
        abbreviation
        name
      }
    }
  }
}

Output:

{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1337",
      "status": "draft",
      "play_positions": [
        {
          "play_positions_id": {
            "id": "1",
            "abbreviation": "RWB",
            "name": "Right Wingback"
          }
        },
        {
         "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}

Since you can add many of those elements, I defined a variable/argument like here

mutation CreateProfile2($cpppi: [create_profiles_play_positions_input]) {
  __typename
  create_profiles_item(data: {status: "draft", play_positions: $cpppi}) {
    id
    status
    play_positions {
      
      play_positions_id {
        id
        abbreviation
        name
      }
    }
  }
}

Variable object for above:

"cpppi": {    
    "play_positions_id": {
      "id": "1"
    },
    "play_positions_id": {
      "id": "2
    }
  }

Output:

{
  "data": {
    "__typename": "Mutation",
    "create_profiles_item": {
      "id": "1338",
      "play_positions": [
        {
        
          "play_positions_id": {
            "id": "2",
            "abbreviation": "CAM",
            "name": "Central Attacking Midfielder"
          }
        }
      ],
    }
  }
}

Schema:

input create_profiles_input {
  id: ID
  status: String!
  play_positions: [create_profiles_play_positions_input]
}

input create_profiles_play_positions_input {
  id: ID
  play_positions_id: create_play_positions_input
}

input create_play_positions_input {
      id: ID 
      abbreviation: String
      name: String
}

At the last both snippets, only the last object with the id "2" will be mutated. I need these to use the defined input type from my backend.


Solution

  • I figured it out. I got it wrong with the brackets in the variable. Here the solution:

    "cpppi": [
        {
          "play_positions_id": {
            "id": "1"
          }
        },
        {
          "play_positions_id": {
            "id": "2"
          }
        }
      ]