sanity-io / GROQ

Specification for GROQ - The Query Language for JSON
https://groq.dev
MIT License
398 stars 15 forks source link

GROQ query order(_createdAt desc) doesn't work for multiple document types at once #101

Closed toddpadwick closed 1 year ago

toddpadwick commented 1 year ago

I have an index listing page component which, handles the listing page for all my blog doc types - articles, masterclasses and reports. This listing page component only queries a single one of these types if included in the param. for example: https://www.coolplanet.io/blog/masterclasses The order of these documents is correctly adhering to order(_createdAt desc) when only a single type is included in the type array, such as the above which is: [ "masterclass"].

However, when the url does not have the appended type param, the same component queries all types ["article", "masterclass", "report"]. In this case, unlike with a single type, that same query does not adhere to the orderBy setting despite the query is exactly the same.
https://www.coolplanet.io/blog You can see the order is wrong, because that first masterclass shown on the page, is not the same first masterclass shown when viewing the masterclass listing page.

So this indicates that there could be a bug whereby orderBy does not work with multiple doc types.

Here is my entries GROQ query import:

export default ({
  types = ["article", "masterclass", "report"], // this is default types when a single type param is not specified
  offset = 0,
  limit = 100,
  industry = null,
  role = null,
  lastId = null,
} = {}) => {
  const sliceString =
    isNaN(limit) || limit === 1
      ? `${offset}...${offset + 1}`
      : `${offset}...${limit + offset}`;
  const typeString = '["' + types.join('","') + '"]';

  const filterString = `[_type in ${typeString}${
    industry ? ` && industry->slug.current == "${industry}"` : ""
  }${role ? ` && role->slug.current == "${role}"` : ""}${
    lastId ? " && _id > " + lastId : ""
  }][${sliceString}] | order(_createdAt desc)`;
  return groq`*${filterString} {
        ...
    }`;
};
toddpadwick commented 1 year ago

Turns out this was an error on my part. I had the | order(_createdAt desc) part of the query after the slice part, rather than before. So instead of: [_type in ["article"]][0...24] | order(_createdAt desc) it should be [_type in ["article"]] | order(_createdAt desc)[0...24]