Tương tác với API GraphQL
Tương tác với API GraphQLThực thi bulk mutations

Thực thi bulk mutations

Gato GraphQL cung cấp các trường mutation "bulk" cho tất cả các mutations trong schema, cho phép chúng ta mutate nhiều tài nguyên cùng một lúc.

Ví dụ, mutation createPosts (mutation cho một tài nguyên đơn lẻ là createPost) sẽ tạo nhiều bài viết:

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
    }
  }
}

Tham số

Tất cả các bulk mutations đều chấp nhận hai tham số:

  • inputs (bắt buộc): Mảng các mục đầu vào, trong đó mỗi mục chứa dữ liệu để mutate một tài nguyên
  • stopExecutingMutationItemsOnFirstError (mặc định false): Cho biết liệu, trong trường hợp bất kỳ đầu vào nào tạo ra lỗi, có nên dừng thực thi mutation trên các đầu vào tiếp theo hay không.

Tất cả các mutations đều được thực thi theo thứ tự được cung cấp trong tham số inputs.

Các trường hợp sử dụng

Bulk mutations mở ra nhiều khả năng để quản lý trang WordPress của chúng ta.

Ví dụ, queries GraphQL sau đây sử dụng createPosts để nhân bản các bài viết:

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
    }
  }
}