Jonhnny Weslley
Jonhnny Weslley

Reputation: 1080

Bulk mutations using GraphQL

I am consuming a third-party GraphQL API and I need to perform several mutations. There is a way to iterate over a list and call the desired mutation? Something like:

mutation ($inputs: [EntityInput!]) {
  // iterate over $inputs and ... {
    entityUpdate(input: $input) {
      entity {
        id
      }
    }
  }
}

Upvotes: 0

Views: 778

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

There's no way to do what you're asking using GraphQL syntax alone. However, you could use string interpolation and field aliases to achieve the same result. Here's what that would look like using JavaScript:

const inputs = [...]
const variableDefinitions = inputs
  .map((_input, index) => `$input${index}: EntityInput!`)
  .join(', ')
const selectionSet = inputs
  .map((_input, index) => `
    entityUpdate${index}: entityUpdate(input: $input${index}) {
      entity {
        id
      }
    }
  `)
  .join('/n')
const query = `
  mutation (${variableDefinitions}) {
    ${selectionSet}
  }
}
`
const variables = inputs.reduce((acc, input, index) => {
  acc[`input${index}`] = input
  return acc
}, {})

This results in a map of variables like $input0, $input1, etc. and a responding query like:

mutation ($input0: EntityInput!, $input1: EntityInput) {
  entityUpdate0: entityUpdate(input: $input0) {
      entity {
        id
      }
    }
  }
  entityUpdate1: entityUpdate(input: $input1) {
      entity {
        id
      }
    }
  }
}

You can utilize a fragment to reduce the duplication among the selection sets and reduce the size of your payload.

Additionally, some servers (like Hot Chocolate) support batching operations inside a single HTTP request. If the server you're querying supports this feature, that would be an alternative way of accomplishing the same goal.

Upvotes: 2

Related Questions