如何在graphql查询中重用fiedls

时间:2017-08-29 21:09:27

标签: graphql graphql-js react-apollo

我知道如何使用片段,我现在的问题是片段只能在类型的查询/突变中使用。

例如

paginationFragment on Person

我想我要找的东西与片段类似,但更为通用。

EG。我有一个PersonBrowseQuery,EventsBrowseQuery,BookmarkBrowseQuery等。所有都有一个包含我的分页数据的元字段

meta {
  total
  per_page
  current_page  

  etc.    
}

是否可以将其归结为可重复使用的东西?

1 个答案:

答案 0 :(得分:4)

您的元字段是一种类型,因此您仍然可以使用它的片段:

const metaFragment = gql`
  fragment MetaFields on MetaType {
    total
    per_page
    current_page  
    # other fields    
  }`

然后,它可以作为使用模板文字占位符语法包含在您的查询中:

const usersQuery = gql`
  query getUsers {
    users {
      meta {
        ...MetaFields
      }
      # other fields
    }
  }
  ${metaFragment}
}`

确保片段的名称(本例中为MetaFields)匹配。 或者,如果您有一些不一定是片段的共享字段,并且您仍然倾向于尽可能保持DRY,那么您可以使用普通的模板文字:

const sharedFields = `
  bar
  baz
  qux
`
const usersQuery = gql`
  query getFoo {
    foo {
      ${sharedFields}
      # other fields
    }
  }
}`