graphqlhasura

Hasura graphql optional generated variable


how can I attach a variable to a mutation conditionally?
I want to create an upsert mutation where the id is generated by the database.
So, if the $id variable was set, make an update, otherwise, a creation.
I have tried something like this:

  mutation upsert (
    $id: uuid
    $name: String
  ) {
    insert_data_one(
      object: {
        id: $id
        name: $name
      }
     on_conflict: {
      constraint: data_pkey
      update_columns: [name ]
    }
    ) {
      id
      name
    }
  }

But the error I receive is a malformed id

{
  "errors": [
    {
      "extensions": {
        "path": "$.selectionSet.insert_data_one.args.object.id",
        "code": "validation-failed"
      },
      "message": "unexpected null value for type \"uuid\""
    }
  ]
}

Solution

  • As an alternative to using named variables for each field, you can accept the whole record as a variable. This way, if a field is not required in this mutation (for example if it is nullable) you can safely leave it out.

    It might look something like this:

    mutation MyMutation($object: data_insert_input!) {
      insert_data_one(object: $object) {
        id
        name
      }
    }
    

    Then your variables might look something like this:

    {
      "object": {
        "id": "<some id>",
        "name": "<some name>"
      }
    }