danielroe/sanity-typed-queries

help: How to make a complex request?

Realetive opened this issue ยท 2 comments

๐Ÿ“š What are you trying to do? Please describe.

firstObject.ts
const { firstObject, object } = defineObject( 'firstObject', {
  uniqueFirst: {
    type: 'localeString',
  },
  author: {
    type: 'reference',
    to: [ { type: 'author' } ],
  },
  schedule: {
    type: 'array',
    of: [
      { type: 'event' }
    ],
  }
}, [
  localeString,
  author,
  event,
] )

export { firstObject }
export default object
secondObject.ts
const { secondObject, object } = defineObject( 'secondObject', {
  uniqueSecond: {
    type: 'localeString',
  },
  author: {
    type: 'string',
  }
}, [
  localeString,
] )

export { secondObject }
export default object
const { builder } = defineDocument( 'doc', {
  mix: {
    type: 'array',
    of: [
      { type: 'firstObject' },
      { type: 'secondObject' },
    ],
  },
}, [
  firstObject,
  secondObject,
] )

const [ query ] = builder
  .map( h => ( {
      mix: h.mix.use() // ??? 
  } ) )
  .pick('mix')
  .first()
  .use()

๐Ÿ” What I want to get?

*[_type == 'doc'] [0] { 'mix': mix[]{ _key, uniqueFirst, uniqueSecond, 'author': author->{ name, title } } }

I can write

builder.map( h => ( {
      mix: 'mix[]{ _key, uniqueFirst, uniqueSecond, 'author': author->{ name, title } }'
  } ) )

but it will return wrong type.

@Realetive With a complex query, you can provide the return type yourself.

type Mix = Array<{
  _key: string
  ...
}>
builder.map(h => ({
  mix: 'mix[]{ _key, uniqueFirst, uniqueSecond, 'author': author->{ name, title } }' as unknown as Mix
}))

Does that work for you?