FormidableLabs / groqd

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

How can I query a nested referenced image in an array #296

Closed Designer023 closed 4 months ago

Designer023 commented 4 months ago

Is there an existing issue for this?

Code of Conduct

Question

Hi, I have a problem accessing an image (referenced) from a block array. I cannot for the life of me access the referenced image within the block.

The data structure is essentially: `body: block(array of fields)` with an `placedImage` field which is an image with some placement fields and a default sanity `image` (reference).

const PlacedImage = q
  .object({
    imageLayout: q.string(),
    image: sanityImage("image"), // is missing the following properties from type ZodType<any, any, any>: _type, _output, _input, _def, and 31 more.
  })

const query = q(`*`)
  .filter(`slug.current == $slug`)
  .grab$({
    thumbImage: sanityImage("thumbImage", {}), // This works as expected
    body: q("body[]", { isArray: true }).select({
      "_type == 'placedImage'": ["@", PlacedImage], // Field with the issue
      "_type != 'reference'": ["@", q.contentBlock()], // Normal block content text field stuff
    }),
  })

Running the query in the playground yields: Error: keyValidator._parse is not a function.

How can I (re)write my query so that I can get the assets back for the image. I'm specifically looking for the blurHash property under body[].placedImage.image.assets->(ref).metadata.blurHash and I have the problem with the reference (->) in the middle of the query.

Any help/suggestions would be greatly appreciated 🙏

Designer023 commented 4 months ago

I've figured it out:

 q(`*`)
  .filter(`slug.current == $slug`)
  .grab$({
  body: q("body[]").filter().select({
     "_type == 'placedImage'": q("@").grab({ 
          image: q.sanityImage("image", { withAsset: ["blurHash"], }),
     }),
    })
  })

The middle example in the docs here gave me the clue: https://commerce.nearform.com/open-source/groqd/docs/query-building#args

Hopefully this will help someone else in the future 👍