[GraphQL] Reuse Query Fields with GraphQL Fragments
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[GraphQL] Reuse Query Fields with GraphQL Fragments相关的知识,希望对你有一定的参考价值。
A GraphQL fragment encapsulates a collection of fields that can be included in queries. In this video, we‘ll look at how to create fragments on types to reduce the amount of typing that needs to occur as queries become more complex. We‘ll use the GitHub API to test.
We have:
# Type queries into this side of the screen, and you will # see intelligent typeaheads aware of the current GraphQL type schema, # live syntax, and validation errors highlighted within the text. # We‘ll get you started with a simple query showing your username! query { organization(login: "moonhighway") { email, url, repository(name: "learning-graphql") { url, description } }, repository(owner:"facebook" name:"graphql"){ url, description, name, languages(first:1){ nodes { name } } } }
To resue ‘url‘, ‘description‘ for Repository, we can create fragment:
fragment CommonFields on Repository {
url,
description
}
Therefore, we can reuse it:
# Type queries into this side of the screen, and you will # see intelligent typeaheads aware of the current GraphQL type schema, # live syntax, and validation errors highlighted within the text. # We‘ll get you started with a simple query showing your username! query { organization(login: "moonhighway") { email, url, repository(name: "learning-graphql") { ...CommonFields } }, repository(owner:"facebook" name:"graphql"){ ...CommonFields name, languages(first:1){ nodes { name } } } } fragment CommonFields on Repository { url, description }
以上是关于[GraphQL] Reuse Query Fields with GraphQL Fragments的主要内容,如果未能解决你的问题,请参考以下文章
[GraphQL] Query GraphQL Interface Types in GraphQL Playground
[GraphQL] Query a GraphQL API with graphql-request
如何在 .graphql 文件中编写 GraphQl Upsert Query
<Query> vs graphql Hoc,这是在 react apollo 中将 graphql 查询与组件挂钩的最佳方法