【问题标题】:Bulk mutations using GraphQL使用 GraphQL 进行批量突变
【发布时间】:2020-11-21 00:09:45
【问题描述】:

我正在使用第三方 GraphQL API,我需要执行几个突变。有一种方法可以遍历列表并调用所需的突变?比如:

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

【问题讨论】:

    标签: graphql


    【解决方案1】:

    仅使用 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 请求中进行批处理操作。如果您查询的服务器支持此功能,那将是实现相同目标的另一种方法。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2020-08-15
      • 1970-01-01
      • 2021-02-17
      • 2018-10-15
      • 2018-07-27
      • 1970-01-01
      • 2018-12-20
      • 2021-03-16
      相关资源
      最近更新 更多