【问题标题】:How to reuse fiedls in graphql queries如何重用graphql查询中的字段
【发布时间】:2018-02-07 10:58:05
【问题描述】:

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

例如。

paginationFragment on Person

我想我正在寻找的内容类似于片段,但更一般。

例如。我有一个 PersonBrowseQuery、EventsBrowseQuery、BookmarkBrowseQuery 等。都有一个包含我的分页数据的元字段

meta {
  total
  per_page
  current_page  

  etc.    
}

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

【问题讨论】:

    标签: graphql graphql-js react-apollo


    【解决方案1】:

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

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

    【讨论】:

    • 对于第二个选项,我得到了这个错误:String interpolation is not allowed in graphql tag:
    猜你喜欢
    • 2019-06-29
    • 2021-01-18
    • 2018-08-04
    • 1970-01-01
    • 2019-06-12
    • 2021-10-10
    • 2020-05-05
    • 2021-05-07
    • 2018-08-17
    相关资源
    最近更新 更多