Search code examples
graphqlapolloprismic.io

How to make a foreach request in Apollo GraphQL?


I have a blog in javascript and I'm using Apollo GraphQL to save my data. I intend to make a list with six posts of all categories. Like this:

[
  technology: [
    post1,
    post2,
    ...
  ],
  cook: [
    post1,
    post2,
    ...
  ],
  ...
]

But I couldn't. I thought in take all categories's id's and make a big request, like this:

{
  firstCategory: allPosts(where: {category: "firstId"}, first: 6) {
    ...fields
  }

  secondCategory: allPosts(where: {category: "secondId"}, first: 6) {
    ...fields
  }
}

But if I add a new category, I must change my code.


Solution

  • You can pass categories [queried earlier] as variables, like:

    query posts($firstCat: String, $secondCat: String, $limit: Int) {
      firstCategory: allPosts(where: {category: $firstCat}, first: $limit) {
        ...fields
      }
      secondCategory: allPosts(where: {category: $secondCat}, first: $limit) {
        ...fields
      }
    }
    

    variables:

    {
      "firstCat": "technology",
      "secondCat": "cook",
      "limit": 6
    }
    

    Of course, it's still limited to n prepared aliases.

    Building dynamic aliases are possible but not adviced - source ... AST tools should be used as gluing strigs (directly or using literals) is considered as abusing GraphQL.

    You can also destructure this component, multiple <Category name="technology" /> components with their own internal query (use props.name as category filter variable). This will make separate requests.

    For speed and SEO purposes you can use gatsby (amount of separate requests doesn't matter ... up to some scale) - but (as all static generators) it requires rebuild/redeploy on changes.

    Good API should let you query for tags and related posts inside each of them (sorted by any criteria; ... and author inside [and his posts] ... etc - it's a standard GraphQL feature).