Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby.js: Filter GraphQL query by nested object property

I'm working on a news site which will have articles, each with one or multiple respective authors. If you click on an author's name, it will take you to a page displaying their information and a list of articles they have contributed to.

So each article has an authors property, which in turn is an array of author objects with properties: full name, slug (lowercase version of full name with spaces replaced by dashes), etc.

Is it possible to filter the articles by a particular author's slug when defining the query?

query authorQuery($slug: String!) {
  allContentfulArticle(filter: { //not sure what to do here }) {
    edges {
      node {
        title
        slug
        authors {
          name
          slug
        }
      }
    }
  }
}

My other option would be to load all of the articles, then setup a filter in the component like so:

const articles = data.allContentfulArticle.edges.filter(({ node }) => {
  return node.authors.some((author) => author.slug === data.contentfulAuthor.slug);
});

This wouldn't be the end of the world, however it goes against the GraphQL principle of only loading the data you need.

like image 814
dougmacklin Avatar asked Jan 30 '18 23:01

dougmacklin


Video Answer


1 Answers

What you want to achieve here if I understood correctly, you want to group articles by author. You can achieve that if you query and apply filter to allContentfulAuthor and request the article field, like so:

{
  allContentfulAuthor(filter: {slug: {eq: "myslug"}}) {
    edges {
      node {
        name
        article {
          title
          slug
        }
      }
    }
  }
}

Note that the article name is your contentTypeId for your articles.

like image 105
Khaled Garbaya Avatar answered Sep 22 '22 07:09

Khaled Garbaya