与 GraphQL API 交互
与 GraphQL API 交互执行批量 mutation

执行批量 mutation

Gato GraphQL 为 schema 中的所有 mutation 提供了「批量」mutation 字段,允许我们一次性对多个资源进行 mutate。

例如,mutation createPosts(单资源 mutation 为 createPost)将创建多篇文章:

mutation CreatePosts {
  createPosts(inputs: [
    {
      title: "First post"
      contentAs: {
        html: "This is the content for the first post"
      }
    },
    {
      title: "Second post"
      contentAs: {
        html: "Here is another content, for another post"
      }
      excerpt: "The cup is within reach"
    },
    {
      title: "Third post"
      contentAs: {
        html: "This is yet another piece of content"
      },
      authorBy: {
        id: 1
      },
      status: draft
    }
  ]) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      title
      content
      excerpt
      author {
        name
      }
      status
    }
  }
}

参数

所有批量 mutation 接受两个参数:

  • inputs(必填):输入项的数组,每个项包含对一个资源进行 mutate 所需的数据
  • stopExecutingMutationItemsOnFirstError(默认值:false):指定当某个输入产生错误时,是否停止对后续输入执行 mutation。

所有 mutation 按照 inputs 参数中提供的顺序依次执行。

使用场景

批量 mutation 为管理 WordPress 站点开启了更多可能性。

例如,以下 GraphQL query 使用 createPosts 来复制文章:

query ExportPostData
{
  postsToDuplicate: posts {
    rawTitle
    rawContent
    rawExcerpt
    postInput: _echo(value: {
      title: $__rawTitle
      contentAs: {
        html: $__rawContent
      },
      excerpt: $__rawExcerpt
    })
      @export(as: "postInputs", type: LIST)
      @remove
  }
}
 
mutation CreatePosts
  @depends(on: "ExportPostData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      title
      content
      excerpt
    }
  }
}