graphqlhasura

Can a mutation be clever enough to not require a trip to get an id first?


I am learning GraphQL as an amateur dev (having a rudimentary knowledge of SQL - enough to have built a home app where I was inserting, joining , upserting data in SQLite).

There was something magical in using Hasura to build the schema of relations between my database tables (so queries are now very simple) and as I am reading about mutating data I have a general question I want to clear up before going further (I am hoping for the same kind of magic).

Consider the following request whose aim is to insert a new record for a user (John Bown) that is an employee of the company "ibm" since "2003". The user and company live in separate tables.

mutation MyMutation {
  insert_users(objects: 
  { 
    user_company: { data: { name: "ibm", date: 2003 } }, 
    first_name: "John", last_name: "Brown" 
}) 
{
    returning {
      id
    }
  }
}

This request works, except that a new user "John Brown" and company "ibm" is created each time.

My question:


Solution

  • GraphQL doesn't feature data management semantics. When you write:

    mutation myMutation {
      insert_users(variables) {
        id
      }
    }
    

    GraphQL only does a few things:

    1. validate that the variables are of the right shape and type and that no required variables are missing
    2. validate that you are asking for fields from the expected type of return object
    3. call the insert_users mutation code with the appropriate context and variables.
    4. limit the return data to whatever you specifically asked for

    It's up to your mutation code to implement the actual intent of your mutation. Your mutation code needs to check for existence of records, insert or upsert as you prefer, generate errors as you see fit and in this case, deal with the proper interrelationships between companies and people. iow all your business logic needs to be in your mutation code, not in GraphQL.