Search code examples
graphqlapollo-clientreact-apollo

React + Apollo / GraphQL: Folder structure for colocation of custom queries?


I am no GraphQL expert so looking for some insights. I have an app that looks like this:

src/
  components/
    FooPage
    BarPage
    BazPage

All 3 pages will make the same queries but with different fields

// FooPage
const GET_DOGS_1 = gql`
  query GetDogs {
    dogs {
      id
    }
  }
`;

// BarPage
const GET_DOGS_2 = gql`
  query GetDogs {
    dogs {
      id
      breed
      name
    }
  }
`;

// BazPage
const GET_DOGS_3 = gql`
  query GetDogs {
    dogs {
      name
    }
  }
`;

I noticed that a lot of apps have a src/graphql folder with files inside it that represent a resource. So in this case it would be something like src/graphql/dogs.ts

However, I don't feel like it makes sense if I am trying to set up my app so that the queries are colocated with the pages because the queries are all going to be specific to each page, which I feel is the whole point of using GraphQL? Since the whole idea is to be able to not overfetch fields that you won't use, and putting them all in one file makes it difficult and forces me to name things like GET_DOGS_1, GET_DOGS_2, etc.

I'm thinking of something more like

src/
  components/
    FooPage/
      queries.ts
      index.tsx
    BarPage/
      queries.ts
      index.tsx
    BazPage/
      queries.ts
      index.tsx

That way:

  1. All pages will be able to specify the fields they want and not overfetch
  2. There will be no name clashing and all pages can just name their respective queries GET_DOGS
  3. It will be colocated with the page, and act as documentation for what API fields are needed for that specific page
  4. The queries decoupled from each other

From your expert opinion, does this sound like a typical GraphQL structure? I don't understand why apps would centralize 1 version of each query. I get it for mutations though since there is usually only one way to POST / create data. Thank you in advance.


Solution

  • Centralizing all GraphQL operations or not is a design choice for you and your team when working on a project.

    Some teams find it more convenient to have all operations in one place. Other teams find it better to have the operations "next to" the components/pages that use them. (this can be applied to other utilities not only GraphQL)

    Take a look into the fullstack tutorial from apollo the queries are defined inside the components/pages that use them, this way it makes it easy to update both query and their usage as we don't have to navigate to multiple files.

    Opinion:

    • If your query is only used by one component/page, keep it inside the same file or right next to it.
    • If your query is used by multiple components/pages, keep it at a top level (src/graphql) to be reused across your application.