GraphQL equivalient to Insert on Duplicate Key Update

When using the @id directive with third-party IDs there are times when I want to do an insert/update depending if the data exists already or not.

I know this can be done with DQL inside of a @custom directive, but then I am limited to field selection and deep graph modeling based upon the returned data.

What would be nice, is if there was a way to indicate in a mutation if I want to update on duplicate key instead of error out.

type Person {
  guid: String! @id
  name: String
}
mutation {
  addPerson(input:[{
    guid: "1"
    name: "Bob"
  } {
    guid: "2"
    name: "Jane"
  }]) {
    numUids
  }
}
# later mutation to add a new user and update an existing in a single mutation
mutation {
  addPerson(input: [{
    guid: "2"
    name: "Jane Doe"
  } {
    guid: "3"
    name: "John Doe"
  }]) {
    numUids
  }
}

This would error out with

couldn’t rewrite query for mutation addPerson because id 2 already exists for type Person

What I would like to be able to do somehow is:

mutation {
  addPerson(input: [{
    guid: "2"
    name: "Jane Doe"
  } {
    guid: "3"
    name: "John Doe"
  }]) {
    numUids
  }
}

Right now with any kind of import/sync script, I have to know what ones we already have and then process something like:

query {
  queryPerson { # yes this could be filtered to just look for matching guids of the incoming data.
    guid
  }
}
#process those returned guids to generate this:
mutation {
  addPerson(input: [{
    guid: "3"
    name: "John Doe"
  }]) {
    numUids
  }
  updatePerson(input: {
    filter: { guid: { eq: "2" } }
    set: { name: "Jane Doe" }
  }) {
    numUids
  }
}

And if I have multiple to update, it gets very hairy…

mutation {
  ...
  up1:updatePerson(input: {
    filter: { guid: { eq: "1" } }
    set: { name: "Bob Smith" }
  }) {
    numUids
  }
  up2:updatePerson(input: {
    filter: { guid: { eq: "2" } }
    set: { name: "Jane Doe" }
  }) {
    numUids
  }
}

Notice how I have alias the updatePerson mutations because I cannot update more than one at a time.

Related issue already under consideration

2 Likes

Thanks, @amaster507, a similar request came up a couple of weeks back. We’ll look into adding support for this soon.

1 Like