[英]GraphQL fragment of fragments
I have a GraphQL query like this:我有一个这样的 GraphQL 查询:
import { gql } from 'apollo-boost';
export default gql`
{
pageHomeCollection(limit: 1) {
items {
navigationLinkLeft {
... on PageBasic {
slug
title
}
... on PageShop {
title
}
... on PostCollection {
slug
title
}
}
navigationLinkRight {
... on PageBasic {
slug
title
}
... on PageShop {
title
}
... on PostCollection {
slug
title
}
}
title
}
}
}
`;
The requested data for both navigationLinkLeft
and navigationLinkRight
are the same, so I'd like to avoid the duplication. navigationLinkLeft
和navigationLinkRight
请求的数据是相同的,所以我想避免重复。 I know about fragments, but not sure if it's possible to extract the 3 ... on
because I'm not sure what type the fragment would be.我知道片段,但不确定是否可以提取 3
... on
因为我不确定片段是什么类型。 Is this possible?这可能吗?
Yes, you can nest fragments.是的,您可以嵌套片段。 Assuming
navigationLinkLeft
and navigationLinkRight
have the same type, you can do something like this:假设
navigationLinkLeft
和navigationLinkRight
具有相同的类型,您可以执行以下操作:
{
pageHomeCollection(limit: 1) {
items {
navigationLinkLeft {
...YourFragment
}
navigationLinkRight {
...YourFragment
}
title
}
}
fragment YourFragment on SomeInterfaceOrUnionType {
... on PageBasic {
slug
title
}
... on PageShop {
title
}
... on PostCollection {
slug
title
}
}
If navigationLinkLeft
and navigationLinkRight
do not have the same type, this won't work.如果
navigationLinkLeft
和navigationLinkRight
不具有相同的类型,这是不行的。 At best, you can only avoid duplicating the fields themselves:充其量只能避免重复字段本身:
{
pageHomeCollection(limit: 1) {
items {
navigationLinkLeft {
...NavigationLinkLeftFragment
}
navigationLinkRight {
...NavigationLinkRightFragment
}
title
}
}
fragment NavigationLinkLeftFragment on PageHomeNavigationLinkLeft {
...PageBasicFragment
...PageShopFragment
...PostCollectionFragment
}
fragment NavigationLinkRightFragment on NavigationLinkRight {
...PageBasicFragment
...PageShopFragment
...PostCollectionFragment
}
fragment PageBasicFragment on PageBasic {
slug
title
}
fragment PageShopFragment on PageShop {
title
}
fragment PostCollectionFragment on PostCollection {
slug
title
}
The above avoids using inline fragments, but you can always use an inline fragment if you don't need to reference a fragment by name elsewhere.上面避免了使用内联片段,但如果您不需要在别处按名称引用片段,则始终可以使用内联片段。 So you can also just do:
所以你也可以这样做:
navigationLinkLeft {
...PageBasicFragment
...PageShopFragment
...PostCollectionFragment
}
navigationLinkRight {
...PageBasicFragment
...PageShopFragment
...PostCollectionFragment
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.