thepixelage / craft-fragments

Fragments is a Craft CMS plugin for managing content and presentational fragments.
https://www.thepixelage.com/plugins/fragments
Other
6 stars 1 forks source link

GraphQL `limit:1` argument results in empty array if first fragment condition does not match #25

Closed denisyilmaz closed 1 year ago

denisyilmaz commented 1 year ago

When a zone has multiple fragments we want to only show the first matching fragment in the frontend. For this we query with the argument limit:1 expecting the first fragment which matches the given uri/id.

Unfortunately it seems the plugin only checks the condition after the limit is set. so it gets all the fragments, limit the result to the first one and then checks if the condition is met.

This results in pages which are not matching to the first fragment to have a empty array.

Example 1:

To list all the fragments available (no fragments have rules at this point)

{
  fragments {
    title
  }
}
{
  "data": {
    "fragments": [
      {
        "title": "Fragment 1"
      },
      {
        "title": "Fragment 2"
      },
      {
        "title": "Fragment 3"
      }
    ]
  }
}

Example 2:

Fragment 1 gets the condition entryUri == 'test-uri'. Here without limit:1. Result is as expected.

{
  shouldShowFragment1: fragments(entryUri:'test-uri') {
    title
  }
  shouldNOTShowFragment1: fragments(entryUri:'not-test-uri') {
    title
  }
}
{
  "data": {
    "shouldShowFragment1": [
      {
        "title": "Fragment 1"
      },
      {
        "title": "Fragment 2"
      },
      {
        "title": "Fragment 3"
      }
    ],
    "shouldNOTShowFragment1": [
      {
        "title": "Fragment 2"
      },
      {
        "title": "Fragment 3"
      }
    ]
  },
}

Example 3:

Fragment 1 gets the condition entryUri == 'test-uri' and we now query with limit:1. This is the result

{
  shouldShowFragment1: fragments(entryUri:'test-uri', limit:1) {
    title
  }
  shouldNOTShowFragment1ButFragment2: fragments(entryUri:'not-test-uri', limit:1) {
    title
  }
}
{
  "data": {
    "shouldShowFragment1": [
      {
        "title": "Fragment 1"
      },
    ],
    "shouldNOTShowFragment1ButFragment2": [
    ],
  },
}
MrRonbot commented 1 year ago

You are right. The behaviour of the limit argument was still the default one provided for GQL queries in Craft. We have now added a modification so that we can apply the limit after we have completed matching of the conditions. This fix is now in version 4.0.1 and it should make the behaviour more aligned to what you are expecting.

denisyilmaz commented 1 year ago

Great, thank you. Just updated our project and tested it. Works like expected!