仅使用 GraphQL 语法无法满足您的要求。但是,您可以使用字符串插值和field aliases 来获得相同的结果。这是使用 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
}, {})
这会生成$input0、$input1 等变量的映射以及如下响应查询:
mutation ($input0: EntityInput!, $input1: EntityInput) {
entityUpdate0: entityUpdate(input: $input0) {
entity {
id
}
}
}
entityUpdate1: entityUpdate(input: $input1) {
entity {
id
}
}
}
}
您可以利用片段来减少选择集之间的重复并减小有效负载的大小。
此外,一些服务器(如Hot Chocolate)支持在单个 HTTP 请求中进行批处理操作。如果您查询的服务器支持此功能,那将是实现相同目标的另一种方法。