5. Fragments

GraphQL 中,fragments 是组织和复用公共字段的方式。比如,我们需要获取博客中一些作者的信息。这么写query:

{
  arunoda: author(_id: "arunoda") {
    _id,
    name,
    twitterHandle
  },
  pahan: author(_id: "pahan") {
    _id,
    name,
    twitterHandle
  },
  indi: author(_id: "indi") {
    _id,
    name,
    twitterHandle
  }
}

上面 Auhtor 中的字段被写了很多次。我们可以使用 Fragments 来避免这样的写法。 让我们看一下如何使用 Fragments

以上代码,相同组的代码被重写了很多次。在这里使用 Fragments 可以解决字段复用的问题。以下代码是用 Fragments 重写的 query

{
  arunoda: author(_id: "arunoda") {
    ...authorInfo
  },
  pahan: author(_id: "pahan") {
    ...authorInfo
  },
  indi: author(_id: "indi") {
    ...authorInfo
  }
}

fragment authorInfo on Author {
    _id,
    name,
    twitterHandle
}

在这里,我们基于 Author 定义了 fragment,而 fragment 包含我们想要的字段。正如上面的query,我们可以通过展开符(...),来使用 fragment 中的字段。

混合 fragment 和 字段

我们可以将 fragment 和 字段 混合在一起。

{
  indi: author(_id: "indi") {
    ...requiredAuthorInfo
    twitterHandle
  }
}

fragment requiredAuthorInfo on Author {
  _id,
  name,
}

这里我们使用 fragment 来获取 idname,同时定义了 twitterHandle 字段。

这里有个问题,如果你再次定义 fragment 中已经存在的字段,会发生什么?

{
  indi: author(_id: "indi") {
    ...requiredAuthorInfo,
    twitterHandle,
    _id // this is already defined in the fragment
  }
}

答案是: Query executed without any issues.

有嵌套字段的 fragments

fragment 中,我们同样可以定义嵌套字段。fragments 非常有用,看以下例子:

{
  post1: post(_id: "03390abb5570ce03ae524397d215713b") {
    ...postInfo
  },
  post2: post(_id: "0176413761b289e6d64c2c14a758c1c7") {
    ...postInfo
  }
}

fragment postInfo on Post {
  title,
  content,
  author {
    name
  },
  comments {
    content
  }
}

在这个 query 中,我们使用了有嵌套字段的 fragment,它请求了带有作者和评论的两篇文章,而不是去写重复字段。

fragments 嵌套 fragments

你可以在其他 fragments 中使用 fragments

{
  post1: post(_id: "03390abb5570ce03ae524397d215713b") {
    ...postInfo
  },
  post2: post(_id: "0176413761b289e6d64c2c14a758c1c7") {
    ...postInfo
  }
}

fragment postInfo on Post {
  title,
  content,
  author {
    ...authorInfo
  },
  comments {
    content,
    author {
      ...authorInfo
    }
  }
}

fragment authorInfo on Author {
  _id,
  name
}

这里我们在 postInfo fragment 中使用 authorInfo fragment。 我们也可以这样改进 query:

{
  post1: post(_id: "03390abb5570ce03ae524397d215713b") {
    ...postInfo
  },
  post2: post(_id: "0176413761b289e6d64c2c14a758c1c7") {
    ...postInfo
  }
}

fragment postInfo on Post {
  title,
  content,
  ...authorInfo
  comments {
    content,
    ...authorInfo
  }
}

fragment authorInfo on HasAuthor {
  author {
    _id,
    name
  }
}

为了做到这些,我们会在后面不同的课程中学习接口。

最后

现在你已经很好地理解了 fragments 以及我们如何使用 GraphQL queries。你也可以使用带有 fragmentsmutations。因为 mutations 只是 queries 的变形。

当我们谈论如何在客户端使用 GraphQL 时,fragments 扮演着重要的角色。我稍后会谈论更多关于其重要性的内容。

results matching ""

    No results matching ""