Search code examples
graphqlgraphql-jsreact-apollo

How to reuse fiedls in graphql queries


I know how to use fragments, my problem right now is that fragments can only be used within queries/mutations for a type.

Eg.

paginationFragment on Person

I guess what I am looking for is similar to fragments but more general.

Eg. I have a PersonBrowseQuery, EventsBrowseQuery, BookmarkBrowseQuery etc. All have a meta field containing my pagination data

meta {
  total
  per_page
  current_page  

  etc.    
}

Is it possible to factor this to a reusable thing?


Solution

  • Your meta field is a type, so you can still use a fragment for it:

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

    It can then be included in your queries as a using template literal place holder syntax:

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

    Just make sure the name of the fragment (MetaFields in this example) matches. Alternatively, if you have some shared fields that aren't necessarily a fragment and you're bent on staying as DRY as possible, you can just use a plain template literal:

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