sanity-io / GROQ

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

Using params in functions (E.g. `*[] | order($orderBy)`) #103

Open m4rrc0 opened 1 year ago

m4rrc0 commented 1 year ago

I have been looking for a solution for this but it is apparently impossible (or at least very impractical; see below).

For example: *[] | order($orderBy) With params { "orderBy": "createdAt"}

The only "not-really-a-solution" I found is this:

*[] | order(select(
  $orderBy == "_createdAt" => _createdAt,
  _id
))

(context: I am using the plugin sanity-plugin-documents-pane and the Sanity studio crashed when trying to do the same for asc)

This is deeply impractical.

Improvements I can come up with:

*[] | order(@[$orderBy])

Or

*[]
{
  ...@,
  "temp": @[$orderBy],
}
| order(temp)
lucaswalter commented 5 months ago

@m4rrc0 Did you ever end finding a workaround that let's you dynamically set orderBy and orderDirection on your sort function?

I'm have this exact same case and currently am stuck trying trying to get a dynamic asc or desc sort working in a single query. Our project makes heavy use of the new typegen cli and string interpolation breaks the generation of types.

const listToolsQuery = groq`
    *[_type == "tool"]
    | order(
        select(
            $orderBy == "rank" => rank,
            $orderBy == "_createdAt" => _createdAt
        )
        // How can I dynamically set 'asc' or 'desc' here from a parameter here?
    )
    {
        "slug": slug.current,
        "rank": rank,
        _createdAt
    }
`;
lucaswalter commented 5 months ago

Further discussion here in the Sanity slack: https://sanity-io-land.slack.com/archives/C011CAT70DD/p1717972385870249

The conclusion here seems that this is not possible right now.

This would be a massive help for us and our project especially with the new launch of the sanity-typegen workflow. Splitting up our query and using string interpolation breaks typegen for this query. We'd really prefer to avoid losing type safety since this is a core query in our app.

Cooksauce commented 4 months ago

I'm currently facing this same issue on a project I am working on. It would help greatly if we could parametrize the sort order while keeping type safety in this type of workflow.