Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created October 25, 2020 10:26
Show Gist options
  • Save SimeonGriggs/7dcf0d09cfd6dfcc0737f6393defc5de to your computer and use it in GitHub Desktop.
Save SimeonGriggs/7dcf0d09cfd6dfcc0737f6393defc5de to your computer and use it in GitHub Desktop.
Sanity Preview URL with sanityClient Fetch
import sanityClient from 'part:@sanity/base/client'
const remoteURL = 'https://example.com'
const localURL = 'http://localhost:8000'
const previewURL =
window.location.hostname === 'localhost' ? localURL : remoteURL
export default function resolveProductionUrl (document) {
if (!document.slug) return null
if (document._type === 'page') {
if (document.slug.current === 'home') {
return `${previewURL}/`
} else if (document.parentPage._ref) {
const query = `*[page._id == '${document.parentPage._ref}']`
sanityClient.fetch(query).then(parent => {
parent.forEach(parentPage => {
return `${parentPage.slug.current}/${previewURL}/`
})
})
}
} else if (document._type === 'post') {
const categoryName = document.categories.length
? document.categories[0]._ref.replace('category-', '')
: null
if (!categoryName || categoryName !== 'blog') {
return false
}
return `${previewURL}/${categoryName}/${document.slug.current}`
} else if (document._type === 'office') {
return `${previewURL}/office/${document.slug.current}`
} else if (document._type === 'agent') {
return `${previewURL}/agent/${document.slug.current}`
}
return `${previewURL}/${document.slug.current}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment