FormidableLabs / groqd

A schema-unaware, runtime and type-safe query builder for GROQ.
https://commerce.nearform.com/open-source/groqd
MIT License
222 stars 17 forks source link

Feature Request: Add configuration for global query filter options #219

Open winterlamon opened 10 months ago

winterlamon commented 10 months ago

We've been using groqd for a marketing website with content completely driven by Sanity, and have run into a few patterns that we have consistently had to add to each query, and it would be awesome if we could set filter options in one place that would apply to all queries to keep the queries cleaner/easier to read.

Case 1: Queries don't exclude drafts by default This case is probably more of a bug, but could be handled via some configuration. Marketers create content in real-time as we are developing, which leads to ZodErrors in builds when someone starts a draft of a document that has not yet been published, and has missing content. We could filter out those documents using something like this:

const query = q("*")
  .filter(`_type == 'someDocument' && !(_id in path("drafts.**")`)
  .grab(...)

but it would be nice if never-published documents are excluded by default. Alternatively, it would be great to be able to apply that filter condition to a config to apply to all queries.

Case 2: Repeated filter conditions We have created variables for some frequently-used filter conditionals, e.g. allowing pages that are not production ready in non-prod environments based on env vars, i18n filters, the aforementioned never-published filter, etc. Most, if not all, of our queries should be using these, which leads to having to include all of them across dozens of queries. It also means if we have to add another filter when the schema changes, we have to change it across all query instances. Instead of having to do something like this:

const query = q("*")
  .filter(`_type == 'someDocument' && someQuerySpecificConditionals && ${hasBeenPublished} && ${i18nFilter} && ${envVisibilityFilter}`)
  .grab(...)

there could be a config where we set it once:

// groqd.config.js

module.exports = {
  includeDrafts: false,
  globalFilters: [
    'customi18nFilter',
    'coalesce(productionReady, true)'
  ]
}
gksander commented 10 months ago

I like these ideas – let me noodle on this a bit, and see if I have any bandwidth to put something together.

As for case 1, one option might be Sanity's new "Perspectives" API, which is likely a bit more foolproof. I wrote a bit about it here.