Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created June 25, 2018 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerge/9cd1423711899287ff22b79087aeb764 to your computer and use it in GitHub Desktop.
Save bjoerge/9cd1423711899287ff22b79087aeb764 to your computer and use it in GitHub Desktop.
Generate default slug w/listener
const {deburr, kebabCase} = require('lodash')
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: '<your priojectId>',
dataset: '<your dataset>',
token: '<your auth token>',
useCdn: false
})
const SOURCE_FIELD = 'title'
const slugify = value => deburr(kebabCase(value))
client
.listen(
'*[_type == $type && !(_id in path("drafts.**"))]',
{type: 'objectWithDefaultSlug'},
{events: ['mutation']}
)
.subscribe(event => {
const document = event.result
// we only want to respond to appear transitions, and skip if source field is missing
// or the slug is already set
if (event.transition !== 'appear' || !document[SOURCE_FIELD] || document.slug) {
return
}
// todo: make sure we generate an unique slug by querying the dataset for existing slugs
client
.patch(document._id)
.set({slug: {_type: 'slug', current: slugify(document[SOURCE_FIELD])}})
.commit()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment