Created
June 25, 2018 10:53
-
-
Save bjoerge/9cd1423711899287ff22b79087aeb764 to your computer and use it in GitHub Desktop.
Generate default slug w/listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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