Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

return a list of posts with any unpublished drafts at the top, where if a published post has a pending draft, that takes its place instead.

1 replies
Last updated: Nov 30, 2020

This was hell to figure out, so I thought i'd share it. But basically, this returns a list of my posts, with any unpublished drafts at the top, where if a published post has a pending draft, that takes its place instead. This is to let me render my entire site in a preview mode where unpublished changes to any content take priority.

*[
  _type == "post" 
  && (
  	// either is a draft
    (_id in path("drafts.**")) ||
    // or is published and doesn't have an equivalent draft
    (
      !(_id in path("drafts.**")) &&
      (count(*[
        _type == "post"
        && (_id in path("drafts.**"))
        && (slug.current == ^.slug.current)
      ]) == 0)
    )
  )
]{
  _id,  
  title,
  slug,
  publishedAt,
} | order(select(defined(publishedAt) => 1,  0) asc, publishedAt desc)

Nov 28, 2020, 6:26 PM

Thanks for sharing, Andrew, really appreciated!

Nov 30, 2020, 12:17 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.