FormidableLabs / groqd

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

Shaping nested objects in the query #200

Closed markomitranic closed 1 year ago

markomitranic commented 1 year ago

Heya folks, thanks for making an awesome abstraction :)

I can't find any info or examples about shaping nested objects during a query. For example, I've borrowed the query from our Arcade and edited it so that it contains an object at invented property stats, and then I assign values to it by providing every field's path explicitly - "attack": ["base.Attack", q.number()]

  q("*").filterByType("pokemon")
  .grab({
    name: q.string(),
    "stats": q.object({
      "attack": ["base.Attack", q.number()],
      "name-again": ["name", q.string()],
    }),
  })

Obviously, this doesn't work :D so, what am I missing?

markomitranic commented 1 year ago

The answer was fairly simple actually! We should probably add it to the docs somewhere. I can open a PR?

  q("*").filterByType("pokemon")
  .grab({
    name: q.string(),
    "stats": q("base")({
      "attack": ["Attack", q.number()],
    }),
  })

The only remaining question would be if i could somehow map fields that are outside of "base" into the new "stats". Any ideas?

heggemsnes commented 1 year ago

Yes, you can do it with an empty "q" like this:

  q("*").filterByType("pokemon")
  .grab({
    name: q.string(),
    stats: q("").grab({
      "attack": ["base.Attack", q.number()],
      "name-again": ["name", q.string()],
    }),
  })