Orderings based on field in custom type

We have a date field in a custom type and would like to order the query response based on this date field rather than "last_publication_date" or "first_publication_date".

The query response is an array of blog posts with the structure:

[
data: {
page_title: 'string',
excerpt: [richText],
content: [richText],
published_date: 'date-string'
},
first_publication_date: 'date-string',
last_publication_date: 'date-string'
]

Orderings based on "first_publication_date" or "last_publication_date" work fine, but we can't order based on the custom "published_date". Is this possible with getStaticProps? Below is our code:

export async function getStaticProps({ previewData }) {
  const client = createClient({ previewData })

const news = await client.getAllByType('news', {
    //limit: 3,
    orderings: [
      // This returns the correct orderings:
      // { field: 'document.last_publication_date', direction: 'desc'}

      // desired orderings:
      { field: 'document.data.published_date', direction: 'desc'}
    ]
  });

return {
    props: {
      news,
    }
  }
}

Hello Jansen,

Thanks for reaching out to us.

To specify an ordering by a field, the path should look like this:

client.getAllByType('news', {
  orderings: {
    field: 'my.news.published_date,
    direction: 'desc'
  },
})

Give this a try and let me know if you need further assistance.

Thanks,
Priyanka

Thank you @Priyanka, this did indeed work.

I have a follow-up question. Can we order the response based off a number field instead of date? For instance ('order' is a field of type 'Number' in our custom type):

const navigation = await client.getAllByType('header_nav_item',
  {
    fetchLinks: ['header_navigation_group.nav_item', 'header_navigation_group.heading', 'header_navigation_group.heading_icon'],
    orderings: [
      { field: 'my.header_nav_item.order', order: 'desc' }
    ]
  });

The above code produces no results.

@jgunderson I found a couple of mistakes in the above code:

  1. orderings should be in an object, not an in array.
  2. The second key property of the orderings object is direction not an order.

So your code should look like this:

const navigation = await client.getAllByType('header_nav_item',
  {
    orderings: { 
      field: 'my.header_nav_item.order', 
      direction: 'desc'
    }

Thanks,
Priyanka